How to inject constructor in controllers by unity on mvc 4
asp.net-mvc-4, c#, dependency-injection, unity-container
Solution
You need to tell ASP.MVC to use your container to resolve them.
Create an controller factory like
/// <summary>
/// Controller factory which uses an <see cref="IUnityContainer"/>.
/// </summary>
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);
}
}
and register it via the ControllerBuilder in the global.asax
var factory = new IocControllerFactory(_container);
ControllerBuilder.Current.SetControllerFactory(factory);
Every time the framework asks for a new controller it now uses your factory which uses your container.
Problem
I'm using unity 1.1 version and i couldn't inject constructor. My code sush as: Registering dependencies in global.asax Application_Startup method: ``` Core.Instance.Container.RegisterType<ICartBusiness, CartBusiness>(); ``` Injecting constructor: ``` private ICartBusiness _business; public FooController(ICartBusiness business) { _business = business; } ``` mvc throwing this exception: No parameterless constructor defined for this object. P.S: i can't use any new version of unity because i'm using too referenced old dlls so i can't use unity.WebApi or unity.Mvc3 dlls. How to do this?