A Quick Guide To Using Ninject In ASP.NET MVC Applications

Ninject is one of the most popular open source Dependency Injection tool for .NET.

Why is Ninject useful?

The vast majority of effort that is invested in software happens after the initial release. Because Ninject makes your software much easier to change, a small up-front time investment will pay huge dividends as time goes on.

Ninject DI

What makes Ninject different?

An obsessive focus on simplicity and ease of use. We’ve seen the value of dependency injection, but were frustrated by the complexity of existing solutions. The goal of Ninject is to make dependency injection accessible to all developers and all projects.

Getting Started

Create a NinjectController class as follows:

public class NinjectControllerFactory: DefaultControllerFactory
 {
 private IKernel ninjectKernel;

public NinjectControllerFactory()
 {
 ninjectKernel = new StandardKernel();
 AddBindings();
 }

protected override IController GetControllerInstance(RequestContext requestContext,
 Type controllerType)
 {
 return controllerType == null
 ? null
 : (IController)ninjectKernel.Get(controllerType);
 }

private void AddBindings()
 { 

 }
 }

Once you have this structure, all that you need to do is add your dependencies in the “AddBindings” section.

So if you have some interfaces that you want to connect with their concrete implementation and pass them to the constructor, you can do something like this:

private void AddBindings()
 { 
 ninjectKernel.Bind<DB>().To<DB>();
 
 ninjectKernel.Bind<IAccountService>().To<AccountService>();
 ninjectKernel.Bind<IFormsAuthService>().To<FormsAuthService>();
 ninjectKernel.Bind<ICompanyService>().To<CompanyService>();
 }

Finally, one more thing to set up is tell your application that you are using NinjectControllerFactory to build the controllers in your application. Therefore, you should add the following line in the Application_Start() method of Global.asax class.

ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

 

  • Leave a Reply