我正在使用Mvc3和Unity.Mvc3来构建可测试和解耦的站点,但我显然做错了事情。Unity无法解析Session_Start中的接口并解决错误的DbContext
在我Application_Start()
我注册的依赖:
// container is a property of the MvcApplication
// and the HierarchicalLifetimeManager should make sure that the registrations
// only last for this request (or should it?)
_container.Register<Interface, Class>(new HierarchicalLifetimeManager())
然后在Session_Start()
我试图解决我的依赖将一些数据保存到会话:
var obj = _container.Resolve<Interface>();
在这一点上,我得到一个例外说Unity不能解析一个接口,但我认为我为那个接口注册了一个类?
我很茫然,而且越来越难找到解决方案。
编辑:
这里是我的全部代码,一些不必要的部分排除在外:
public class MvcApplication : System.Web.HttpApplication
{
// as EDIT 2 says, this is wrong...
//private IUnityContainer _container = new UnityContainer();
protected void Application_Start()
{
// mvc stuff, routes, areas and whatnot
// create container here and it works, almost
var container = new UnityContainer();
// register dependencies
string connectionString = "String from config";
container.RegisterInstance<DbContext>(new CustomContext(connectionString), new HierarchicalLifetimeManager())
.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager())
.RegisterType(typeof(IRepository<>), typeof(Repository<>), new HierarchicalLifetimeManager());
// register controller resolver
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
// if i try to resolve repos here, it works and they all have the same context
// just like the unit of work
}
protected void Session_Start()
{
// here the container complains that it can't resolve the interface
// wrong
//var userRepo = _container.Resolve<IRepository<User>>();
// right, but still failes, because it is resolving DbContext
// instead of using the CustomContext instance
var userRepo = DependencyResolver.Current.GetService<IRepository<User>>();
// save some user data to session
}
}
public class SampleController : Controller {
// here the container tries to resolve the System.Data.Entity.DbContext
// instead of just giving the repo that instance that I registered
public SampleController(IRepository<Entity> repo) {
}
}
我明明在这个单位-的工作,依赖注入的东西惨遭失败,和最糟糕的部分是,我不知道为什么... 所以请在我开始拔牙之前帮忙。
编辑2:
晴那里。如果我像上面那样创建容器,则在Session_Start()
中失败。如果我将它作为局部变量在Application_Start()
中创建,并使用DependencyResolver
,则它可以工作。如何和为什么,击败我?
但它仍然试图解决DbContext
而不是CustomContext
实例。
SOLUTION:
好了,所以这里的交易:如在编辑2所描述的,利用本地容器变量解决了
:
问题1)访问容器中Session_Start()
,并通过DependencyResolver
作品访问容器。
问题2)解决注册分贝上下文实例:
事实证明,注册一个实例不起作用。 这确实不过:
container.RegisterType<DbContext, CustomContext>(null, new HierarchicalLifetimeManager(), new InjectionConstructor(connectionString))
但我真的不觉得满意,因为我还没有搞清楚为什么这是这样工作的。看起来我需要长时间阅读一本书或一次。
非常感谢提前。
你从哪里得到_container? – drch 2013-02-13 19:13:27
我在MvcApplication类中创建一个实例,'private IUnityContainer _container = new UnityContainer();' – Pinetree 2013-02-13 19:15:12