Web API 2 and ninject, how to make them work together

Full source code to download.

I’ve been using ninject for a few years, but every time I use it with Web Api I hit some problem and they usually stem from not including the right nuget packages, not changing the DependencyResolver or (once) forgetting how to make a binding!

For my future self and your reference, here is how it is done.

1. Nuget packages

Add Ninject.Web.WebApi using nuget to your Web Api project.

That will install two other package dependencies: Ninject Ninject.Web.Common To make everything work you need to add one more nuget package Ninject.Web.Common.WebHost This will pull down the WebActivatorEx package and add a new class called NinjectWebCommon to your App_Start directory.

2. Edit NinjectWebCommon.cs

NinjectWebCommon.cs is missing a key feature if you want to use ninject to construct the controllers, and I presume that is why you are using ninject inside a Web Api project.

In the CreateKernel() method add the second line shown below. Now ninject will be used to resolve controller dependencies.

2GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
3return kernel;

You will need to add a couple of using statements too -

1using System.Web.Http;
2using Ninject.Web.WebApi;

3. Register some services

To actually register some services we move to the RegisterServices(..) method do some binding.

private static void RegisterServices(IKernel kernel)

4. Use it all

And here is the usage in the controller.

 1    public class ValuesController : ApiController
 2    {
 3        private readonly ICaclulator _caclulator;
 4        public ValuesController(ICaclulator calculator)
 5        {
 6            _caclulator = calculator;
 7        }
 9        public int Get(int num1, int num2)
10        {
11            return _caclulator.Add(num1, num2);
12        }
13    }

Full source code to download.

comments powered by Disqus