问题解决与Unity的依赖关系
一旦我试图解决我的unitOfWork我得到这个错误:
“IUnitOfWork类型没有可访问的构造函数。”
但是,只有当我将unitOfWork的LifetimeManager设置为PerResolveLifetimeManager时才会发生这种情况。 如果我只是使用默认的,一切正常。 我的unitOfWork,有一个公共无参数构造函数。 这是我的代码:
//Global asax IUnityContainer unity = new UnityContainer(); unity.RegisterType(); unity.RegisterInstance(new UnitOfWork(), new PerResolveLifetimeManager()); ControllerBuilder.Current.SetControllerFactory(new IocControllerFactory(unity)); //IocControllerFactory public class IocControllerFactory : DefaultControllerFactory { private readonly IUnityContainer _container; public IocControllerFactory(IUnityContainer container) { _container = container; } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType != null) return _container.Resolve(controllerType) as IController; else return base.GetControllerInstance(requestContext, controllerType); } } //Home controller constructor public HomeController(IUnitOfWork unitOfWork) { }
您可以在调用
RegisterInstance
方法时指定以下Unity内置生命周期管理器类型之一或您的自定义类型:
- ContainerControlledLifetimeManager
- ExternallyControlledLifetimeManager
- HierarchicalLifetimeManager
注意:将
PerResolveLifetimeManager
或TransientLifetimeManager
与RegisterInstance
一起使用是PerResolveLifetimeManager
,因为它们都会在每次要解析的调用上创建一个新实例。
从Unity 2.0的官方文档中 ,请查看使用RegisterInstance方法使用Lifetime Manager一节。
当您想要使用unity Container注册现有对象时使用RegisterInstance。每当有此类型的请求时,返回相同的对象实例(而不是新对象)。 默认情况下,RegisterInstance方法具有ContainerControlledLifetimeManager,它在Container的生命周期内管理一个实例。
在PerResolveLifetimeManager的情况下,每次请求解析时,都会创建一个新的对象实例。
因此,当您尝试使用PerResolveLifetimeManager和RegisterInstance方法时。错误将被抛回给您。