This time, I would like to show off the tricks I used to get Ninject working in MVC 4, to archive dependency injection. But you don't need to go through all the hustle if you are using MVC 3.
After creating an empty MVC 4 project, the first thing I realised was there were some framework changes in comparison to MVC 3. Most obvious changes happen in Global.asax.cs, which moves all the configuration setting registers into separate class files in the folder App_Start.
This actually prevents me from using Ninject.MVC3 like I used to do in MVC 3. Even more unfortunately is that Ninject package for MVC 4 is not out yet, that why this alternative solution is used.
NOTE: By the time I am updating this blog, Ninject for MVC 4 has been available for a white, and I am sure there are cleaner and better ways to implement dependency injection. But carry on reading if you are still interested in the though process, and have fun!
Add ‘Ninject.MVC3’ package
You will see NinjectWebCommon.cs file is generated inside ‘App_Start’ folder, which was meant to be part of package adding process.
Modify ‘Global.asax.cs’
Inherit MvcApplication from NinjectHttpApplication instead of HttpApplication
Implement OnApplicationStarted method inherited from NinjectHttpApplication, and move all registers in Application_Start this method to support the normal usage of those functions
Implement CreateKernel method and register your own services
Modify controller
Introduce service into controller constructor before consumption.
Delete ‘NinjectWebCommon.cs’
By specifying client endpoint, the service injection is done.