Dependency Injection Using Ninject In ASP.NET MVC

In this post I will write about how one can quickly get started with Ninject Dependency Injection framework in your ASP.NET MVC application.
 
Step 1

Create a NinjectControllerFactory  
  1. public class NinjectControllerFactory: DefaultControllerFactory {  
  2.         private IKernel ninjectKernel;  
  3.         public NinjectControllerFactory() {  
  4.             ninjectKernel = new StandardKernel();  
  5.             AddBindings();  
  6.         }  
  7.         protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) {  
  8.             return controllerType == null ? null : (IController) ninjectKernel.Get(controllerType);  
  9.         }  
  10.         private void AddBindings() {  
  11.             ninjectKernel.Bind < IAccountService > ().To < AccountService > ();  
  12.             // add your bindings here as required    
  13.         } 
This class derives from DefaultControllerFactory class.
 
The main method that you have to keep in mind here is the "AddBindings" private method. Basically, this is where you will bind your interface's implementations that you want to inject. You will add bindings for each of your services that you would like to be available to your controllers from here.
 
Step 2

Register NinjectFactory in Global.asax
  1. ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); 
 That's it!
 
Now you can inject the services in your controller class like this:
  1. public AccountController(  
  2.            IFormsAuthService _formsService,  
  3.            IAccountService _accountService,  
  4.            IEmailService _emailService,  
  5.            IUserActivityService userActivityService)  
  6.        { 
I hope you found this post useful.
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now