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.
This is how to do it:
- Install the NuGet packages Ninject.MVC3 and Ninject.Extensions.Conventions to your MVC3 project
- Open the NinjectWebCommon class located in the App_Start folder (this was added by the Ninject.MVC3 package)
- Add "using Ninject.Extensions.Conventions;" to the using statements at the top of the class
- Add the following line of code to the RegisterServices method:
kernel.Bind(x => x .FromAssembliesMatching("*") .SelectAllClasses() .BindDefaultInterface());
Subscribe or Follow Me For Updates
Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.
- Subscribe on YouTube at https://www.youtube.com/JasonWatmore
- Follow me on Twitter at https://twitter.com/jason_watmore
- Follow me on Facebook at https://www.facebook.com/JasonWatmoreBlog
- Follow me on GitHub at https://github.com/cornflourblue
- Feed formats available: RSS, Atom, JSON
Other than coding...
I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.
- Subscribe on YouTube at https://www.youtube.com/TinaAndJason
- Follow us on Instagram at https://www.instagram.com/tinaandjason
- Follow us on Facebook at https://www.facebook.com/TinaAndJasonVlog
- Visit our website at https://tinaandjason.com.au
Need Some ASP.NET Help?
Search fiverr to find help quickly from experienced ASP.NET developers.