Dependency injection in ASP.NET Web API 2.1 with Ninject

For a project I am working on, I wanted to unit test ASP.NET Web API 2.1 controllers.

I searched how I could inject dependencies into Web API 2.1 controllers with Ninject but did not find any documentation explaining it. The process is actually quite simple but I decided to describe it anyway, maybe it saves someone's time when investigating it.

First of all I added a constructor that receives the dependencies I need in my controller.

public class ProductsController : ApiController
{
    public readonly IMyDependency myDependency;
    public readonly IAnotherDependency anotherDependency;

    public ProductsController(IMyDependency myDependency, IAnotherDependency anotherDependency)
    {
        this.myDependency = myDependency;
        this.anotherDependency = anotherDependency;
    }

    // GET: api/Products
    public IEnumerable<string> Get()
    {
        return new[] { "value1", "value2" };
    }

    .....
}

This will compile (provided we have defined the types IMyDependency and IAnotherDependency) but if we try to access the API we will get an HTTP 500 error because there is no parameterless constructor defined.

Next, we add Ninject to the project to have it creating the dependency objects for us. Go to the Package Management Console (or to the Manage Nuget Packages dialog) and add the package Ninject Web Host for WebApi 2.

2

If you defined concrete classes as parameters of your constructor you are done! You can access the API and Ninject will take care of injecting instances of your dependencies to the class.

If you defined interfaces in the constructor, as I did, you need a bit more magic to make it work. Ninject does not know which class it needs to instantiate for providing to the constructor. We have to tell it what to do.

If you look in the folder App_Start of your Web API you will find a file NinjectWebCommon.cs. This was added by Ninject's nuget package. Locate the method RegisterServices and define which concrete type should be instantiated per interface:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind<IMyDependency>().To<MyDependency>();
    kernel.Bind<IAnotherDependency>().To<AnotherDependency>();
} 

And that is it. You added dependency injection to your controller! You should be able to call your API and start unit testing the controllers.

comments powered by Disqus