Ninject and ASP.NET MVC 5

It has been a while since my last blog post, and I decided to continue series of simple examples of dependency injection (DI). Last time I had an example of not so well known but extremely simple and fast Simple Injector. This time I wanted to replace the Simple Injector with a more popular Ninject, and see if there are any big differences in terms of set up. I chose Ninject mostly just because of the Japan-related name:)

link image

Goal

My goal is to use an existing source code from a previous Simple Injector blog post, and replace Simple Injector with Ninject.

Go Ninja Go

Our plan is very straightforward:

  1. Remove Simple Injector.
  2. Install Ninject.
  3. Register TestService.

Removing Simple Injector

To get rid of Simple Injector you need to uninstall the nuget packages, remove references and container set up code. Your global.asax code should look like this after the clean up.

using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace WebApplication1
{
    public class MvcApplication : HttpApplication
    {
        protected void Application_Start()
        {
            // default MVC stuff
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}

Now the application’s code should compile, however the application would crash on the start due to missing dependency injection.

Installing Ninject

You should just need to install Ninject extension for MVC5 using the following Nuget command.

Install-Package Ninject.MVC3

This will install Ninject itself and other dependencies. Very straightforward.

Register the TestService

This might look a little bit tricky in the beginning. While you might be used to set up DI in global.asax, however recommended approach for Ninject is to use generated NinjectWebCommon.cs file which could be found in App_Start folder in the web application. See image below.

ninject-web-commo

Now let’s register our TestService in the RegisterServices() method in NinjectWebCommon.cs.

/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<ITestService>().To<TestService>();
}

That’s it! Compile and run the web application, and you should get the same “111” output as using Simple Injector.

The bottom line

I like Ninject MVC extension approach to keep services registration outside of global.asax which makes code cleaner, and everything just worked. Ninject seems to have much more extension options than Simple Injector and I guess this will be interesting to look into it in future blog posts.