Published: March 15 2012

Dependency Injection in 1 line with MVC3 and Ninject

Dependency injection is a must have in any well designed, loosely coupled system. And is absolutely necessary if you plan (and you should!) to use unit testing and TDD.

Up until recently, it was quite fiddly to add DI to a project. It involved downloading 3rd party libraries, modifying config files, and writing code to map each interface to it's concrete implementation.

But now with the help of the NuGet and the Ninject extensions Ninject.MVC3 and Ninject.Extensions.Conventions, you can get dependency injection up and running with just 1 line of code!

This is how to do it:

  1. Install the NuGet packages Ninject.MVC3 and Ninject.Extensions.Conventions to your MVC3 project
  2. Open the NinjectWebCommon class located in the App_Start folder (this was added by the Ninject.MVC3 package)
  3. Add "using Ninject.Extensions.Conventions;" to the using statements at the top of the class
  4. Add the following line of code to the RegisterServices method:
kernel.Bind(x => x
    .FromAssembliesMatching("*")
    .SelectAllClasses()
    .BindDefaultInterface());

 


Need Some ASP.NET Help?

Search fiverr for freelance ASP.NET developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by