I use a different approach using Ninject
- Using NuGet I downloaded Ninject(just it without any special modification for MVC). So you will have Ninject in references.
Now I create a custom controller factory class (class derived from DefaultControllerFactory).My goal is to make MVC use my controller factory when it tries to create a controller object.
public class NinjectControllerFactory : DefaultControllerFactory
{
#region Member Variables
private IKernel ninjectKernel = null;
#endregion
public NinjectControllerFactory(IKernel kernel)
{
this.ninjectKernel = kernel;
AddBindings();
}
private void AddBindings()
{
//BO
ninjectKernel.Bind<IAuthenticationBO>().To<AuthenticationBO>();
//DAO
ninjectKernel.Bind<ISharedDAO>().To<SharedDAO>();
}
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType);
}
}
Make MVC to use my custom controller factory. In Global.asax in Application_Start()
public class MvcApplication : System.Web.HttpApplication
{
private IKernel kernel = new StandardKernel();
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//register a cutom controller factory
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(kernel));
}
}
So now when MVC creates controller objects it uses our custom controller factory and as you saw it resolves all dependencies using Ninject.
For example
public class MainController : Controller
{
#region Member Variables
private IAuthenticationBO authentication = null;
#endregion
public MainController(IAuthenticationBO authentication)
{
this.authentication = authentication;
}
}
Ninject injects the implementation of IAuthenticationBO (in our case AuthenticationBO) and we can use it. Also it's very easy to use mocking and TDD, but it's beyond the scope of the question.