How to use Ninject IoC with ASP.NET MVC
September 29. 2009
3 Comments
- Posted in:
- Tutorial
The following are the detailed steps to use Ninject IoC with ASP.NET MVC
Download and install TortoiseSVN
TortoiseSVN is a Subversion client that allows you to manage source control tasks from within Windows Explorer.Download the source code for Ninject from google code
The Ninject source code is hosted in Google Code website. To download the code to PC, we will use TortoiseSVN. Before that we need the URL of the repository. This is available in the following url: http://code.google.com/p/ninject/source/checkout



Build the Ninject source code
Once we have the source code, we need to build it to generate the two assemblies we need. We will run the Build.cmd file that will trigger a Nant build script which will eventually build the entire source.

Create a new MVC project
Now, let us create a new MVC project using Visual Studio 2008.



Making the MVC project a meaningful project
Before jumping into adding references to the Ninject assemblies, let us modify this MVC project to do something useful. We are going to create an application that will help us browse through the bills in a Parliament. The Parliament has two chambers. House of Lords and House of Commons and each have their own bills at anytime which they are legislating about. I am going to show only the code relevant to this topic, so will not show in detail all the steps in creating this. The source code for this can be downloaded to view the complete implementation minus Ninject integration. Some screen shots of the application is shown below:Home Page

Bills page

Bills in House of Lords

Bills in House of Commons


The case for Dependency Injection
The List of Bills displayed in the website is at the moment “fake” data coming from a class called “FakeDepository”.Code Snippet
- namespaceJoeBloggsStore.DataModel.Concrete
- {
- publicclassFakeDataRepository : IDataRepository
- {
- // fake list of bills in house of lords
- privatestaticIQueryable<string> lordsBills = newList<string>{
- "Live Music Bill [HL]",
- "Constitutional Reform Bill [HL]"
- }.AsQueryable();
- // fake list of bills in house of commons
- privatestaticIQueryable<string> commonsBills = newList<string>{
- "Maximum Wage Bill",
- "Bankers' Pensions (Limits) Bill"
- }.AsQueryable();
- publicIQueryable<string> LordsBills
- {
- get { returnlordsBills; }
- }
- publicIQueryable<string> CommonsBills
- {
- get { returncommonsBills; }
- }
- }
- }
Code Snippet
- publicActionResultLords()
- {
- ViewData["House"] = "Lords";
- ViewData["Bills"] = newFakeDataRepository().LordsBills.ToList();
- returnView("Index");
- }
- publicActionResultCommons()
- {
- ViewData["House"] = "Commons";
- ViewData["Bills"] = newFakeDataRepository().CommonsBills.ToList();
- returnView("Index");
- }
Programming to an Interface
The following code shows the modified BillController that takes in an IDataRepository in it’s constructor. (Lines 5 up to 10 in Figure) The interface variable “dataRepository” is then used to get the Bills (Line 24 and 30 in Figure)Code Snippet
- namespaceJoeBloggsStore.Controllers
- {
- publicclassBillController : Controller
- {
- privateIDataRepositorydataRepository;
- publicBillController(IDataRepositoryrepos)
- {
- this.dataRepository = repos;
- }
- //
- // GET: /Bill/
- publicActionResultIndex()
- {
- ViewData["House"] = "Parliament";
- ViewData["Bills"] = null;
- returnView();
- }
- publicActionResultLords()
- {
- ViewData["House"] = "Lords";
- ViewData["Bills"] = this.dataRepository.LordsBills.ToList();
- returnView("Index");
- }
- publicActionResultCommons()
- {
- ViewData["House"] = "Commons";
- ViewData["Bills"] = this.dataRepository.CommonsBills.ToList();
- returnView("Index");
- }
- }
- }
Integrating Ninject for Constructor Injection
The BillController depends on an appropriate instance of IDataRepository to be passed when it’s constructed using the constructor. By default, MVC Framework creates an instance of BillController by using a parameterless constructor. In our case, we have want MVC to call our constructor with IDataRepository parameter and pass in the correct instance that we will configure. To instruct the MVC framework to do this, we have to modify the Global.asax.cs. The default Global.asax.cs file is as follows:Code Snippet
- namespaceJoeBloggsStore
- {
- // Note: For instructions on enabling IIS6 or IIS7 classic mode,
- // visit http://go.microsoft.com/?LinkId=9394801
- publicclassMvcApplication : System.Web.HttpApplication
- {
- publicstaticvoidRegisterRoutes(RouteCollectionroutes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(
- "Default", // Route name
- "{controller}/{action}/{id}", // URL with parameters
- new { controller = "Home", action = "Index", id = "" } // Parameter defaults
- );
- }
- protectedvoidApplication_Start()
- {
- RegisterRoutes(RouteTable.Routes);
- }
- }
- }
Code Snippet
- publicclassMvcApplication : Ninject.Framework.Mvc.NinjectHttpApplication



- CreateKernel()
- RegisterRoutes(RouteCollection)
- Ensure the Routing still works (because the Application_Start() is now moved into NinjectHttpApplication and RegisterRoutes is also made abstract in NinjectHttpApplication)
- Create a configuration that tells Ninject to inject FakeDepository whenever IDataRepository is requested.
Code Snippet
- protectedoverridevoidRegisterRoutes(RouteCollectionroutes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- routes.MapRoute(
- "Default", // Route name
- "{controller}/{action}/{id}", // URL with parameters
- new { controller = "Home", action = "Index", id = "" } // Parameter defaults
- );
- }

Code Snippet
- namespaceJoeBloggsStore
- {
- publicclassWebModule : StandardModule
- {
- publicoverridevoidLoad()
- {
- Bind<IDataRepository>().To<FakeDataRepository>().Using<OnePerRequestBehavior>();
- }
- }
- }
Code Snippet
- protectedoverrideNinject.Core.IKernelCreateKernel()
- {
- IModule[] modules = newIModule[] { newAutoControllerModule(Assembly.GetExecutingAssembly()), newWebModule() };
- returnnewStandardKernel(modules);
- }
Code Snippet
- <httpModules>
- <add name="ScriptModule"type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
- <add name="UrlRoutingModule"type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
- <add name="OnePerRequestModule"type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/>
- </httpModules>
Code Snippet
- publicoverridevoidLoad()
- {
- //Bind<IDataRepository>().To<FakeDataRepository>().Using<OnePerRequestBehavior>();
- Bind<IDataRepository>().To<SQLDataRepository>().Using<OnePerRequestBehavior>().WithConstructorArgument("connectionString", WebConfigurationManager.ConnectionStrings["ApplicationServices"]);
- }
Comments
An excellent tutorial, thank you very much! I want to add though, that you didn't mention this explicitly, but the Application_Start() method in the MvcApplication class needs to be marked as 'new'
mgroves[...] to Vote[Del.icio.us] How to use Ninject IoC with ASP.NET MVC « Peak bytes (1/24/2011)Monday, January 24, 2011 from [...]
ASP.NET MVC Archived Buzz, Page 1Really a excellent and easy tutorial for learning ninject,
Kishore K BarikIs this possible to a separate class from separate class library using reflection not by direct referencing in Load function of WebModule, if possible how it can be achieved, please reply me.