Issue resolving dependencies with Unity

匿名 (未验证) 提交于 2019-12-03 00:58:01

问题:

As soon as i'm trying to resolve my unitOfWork i get this error :

"The type IUnitOfWork does not have an accessible constructor."

However this only happens when i set the LifetimeManager of the unitOfWork to PerResolveLifetimeManager. If I'm just using the default one, everything works fine. My unitOfWork, do have a public parameterless constructor. This is my code :

//Global asax IUnityContainer unity = new UnityContainer(); unity.RegisterType<HomeController>(); unity.RegisterInstance<IUnitOfWork>(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) { } 

回答1:

You can specify one of the following Unity Built-In Lifetime Managers types or your custom type when you call the RegisterInstance method:

  1. ContainerControlledLifetimeManager
  2. ExternallyControlledLifetimeManager
  3. HierarchicalLifetimeManager

Note: It is not appropriate to use either PerResolveLifetimeManager or TransientLifetimeManager with RegisterInstance since they both create a new instance on every call to resolve.

Taken from the official documentation on Unity 2.0, check the section on Using a Lifetime Manager with the RegisterInstance Method.



回答2:

RegisterInstance is used when you want to register an existing object with unity Container.Each time there is a request for this type , the same instance of object is returned(instead of new object). By default RegisterInstance method has ContainerControlledLifetimeManager which manages one instance throught the lifetime of Container.

In the case of PerResolveLifetimeManager, Each time a request is made to resolve, a new instance of object is created.

Thus when you try to use PerResolveLifetimeManager along with RegisterInstance Method.The error is thrown back to you.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!