Create class DependencyInjectionControllerFactory:
/* * We need to create a class that derives from DefaultControllerFactory * and override GetControllerInstance */ public class DependencyInjectionControllerFactory : DefaultControllerFactory { public DependencyInjectionControllerFactory() { /* * First thing we have to do is to initialize the Dependency * injection service provider (DISP) providig the type of * container that we want to use (Ninject, structuremap, * etc.) and a list "Service" instances to declare each * dependency. */ DependencyInjectionServiceProvider.Initialize( IoCContainerTypeEnum.Ninject, //IoC contaner to be used new List<Service>() //List of dependencies { new Service() { Scope = ScopeEnum.Singleton, SourceType = typeof(IRepository<User>), TargetType = typeof(UserRepository) } } ); } /* * The default controller constructor will then use our Dependency * injection service provider (DISP) to get the instance that will satisfy * the dependency. */ protected override IController GetControllerInstance(RequestContext context, Type controllerType) { return (IController)DependencyInjectionServiceProvider.Get(controllerType); } }
Modify Global.asax.cs
protected void Application_Start() { //Common ASP.NET MVC3 Application_Start() code... AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); //Override default Controller builder to provide dependency injection ControllerBuilder.Current.SetControllerFactory(new DependencyInjectionControllerFactory()); }