DI with Ninject for an MVC project

This seems to be a somewhat moving target with ASP.Net MVC moving up the versions as well as Ninject. This particular target will be ASP.Net MVC 2.0 and Ninject 2.0.

First set up the references:

  1. Download Ninject.Web.Mvc (If not using git, there is a download source link on the page).
  2. Open the mvc2/Ninject.Web.Mvc.sln and compile with release settings.
  3. Copy the files Ninject.dll and Ninject.Web.Mvc.dll from the mvc2/build/debug/release folder to the lib folder of your MVC project.
  4. Add references to these two files to your MVC project.

The DI Container (called a Kernel with Ninject) needs initializing on app startup which, with MVC, is in the Global.asax. Add the following using statements to the Global.asax:

using Ninject;
using Ninject.Modules;
using Ninject.Web.Mvc;

Change the MvcApplication so it inherits from NinjectHttpApplication:

public class MvcApplication : NinjectHttpApplication {

Let Visual Studio implement the CreateKernel method.

override the OnApplicationStarted method copying in the lines from the Application_Start method:

protected override void OnApplicationStarted() {
    AreaRegistration.RegisterAllAreas();
    RouteRegistrar.RegisterRoutes(RouteTable.Routes);
}

Then delete the Application_Start method.

Ninject stores the rules it uses to return class instances in Modules which are derived from NinjectModule. Add the following class to the MVC project:

using Ninject.Modules;

namespace MvcApp.Web {
    public class WebModule : NinjectModule {
        #region Instance Methods

        public override void Load() {
        }

        #endregion
    }
}

The Load method is where we specify how each request for a concrete class is fulfilled.

Lastly, modify the CreateKernel method so that the module is passed into the Kernel’s ctor:

protected override IKernel CreateKernel() {
    var modules = new INinjectModule[]
                      {
                          new WebModule()
                      };
    var kernel = new StandardKernel(modules);
    return kernel;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.