Idea from this post.
By default, MVC2 can’t handle ctor injection.
[HandleError] public class HomeController : Controller { private readonly IGreatingService _greatingService; public HomeController(IGreatingService greatingService) { _greatingService = greatingService; } public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!" + _greatingService.SayHello(); return View(); } }
Solution: A custom ControllerFactroy can be set in App_start.
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); ControllerBuilder.Current.SetControllerFactory(IoC.GetControllerFactory()); } public static class IoC { public static IKernel Kernel; static IoC() { // ObjectFactory.Initialize(x => x.AddRegistry(new ControllerDependencyRegistry())); Kernel = new StandardKernel(new ControllerModule()); } public static IControllerFactory GetControllerFactory() { return new ControllerFactory(); } public static object Get(Type type) { // return ObjectFactory.GetInstance(type); return Kernel.Get(type); } } public class ControllerFactory : DefaultControllerFactory { protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { if (controllerType == null) { return base.GetControllerInstance(requestContext, controllerType); } return IoC.Get(controllerType) as Controller; } } // Ninject implementation public class ControllerModule : NinjectModule { public override void Load() { Bind<IGreatingService>().To<GreatingService>(); } } // StructureMap implementation public class ControllerDependencyRegistry : Registry { public ControllerDependencyRegistry() { For<IGreatingService>().Use<GreatingService>(); } }