Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue resolving dependencies with Unity

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)
{
}
like image 961
Krika Avatar asked Nov 18 '25 18:11

Krika


1 Answers

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.

like image 149
Ibrahim Najjar Avatar answered Nov 21 '25 06:11

Ibrahim Najjar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!