Using Ninject with ASP.NET Web Api 2

Tags: .NET, C#, DI

Dependency Injection in Web Api 2 has changed. For this purpose the NuGet packages for Ninject has been updated adding some breaking changes. If you have used Ninject before and tried the same approach to Web Api 2 or you're updating your Web Api project then it might not work.

Adding the Ninject package is really simple but you need to know which packages to add.

The following packages should be added in the specified order. Open the NuGet Package Manager Console and add the following:

 

install-package Ninject.Web.WebApi
install-package Ninject.Web.WebApi.WebHost

 

Both libraries at the time of writing are 3.2.4.

You can install Ninject.Web.WebApi.WebHost only and it will install the Ninject.Web.WebApi as well. But in my case it installs Ninject.Web.WebApi.WebHost 3.2.4 but Ninject.Web.WebApi will be 3.2.0.0 because that's the minimum version Ninject.Web.WebApi.WebHost depends on. And this throws an HttpConfiguration activation error.

If you follow the two-step process described  above it will work.

The file NinjectWebCommon will be added to the App_Start folder. You need to the RegisterServices method and add your binding, like this

 

kernel.Bind<IUserRepository>().To<UserRepository>();

           

I've created a sample project you can checkout https://github.com/ralbu/ninjectwithwebapi2

Comments

comments powered by Disqus