Quick tip: How to Make Ninject work with ASP.NET Web API

Dependency Injection is something which comes along with almost every new project we are building nowadays. I've recently used Web API several times from it's alpha version and now to the latest versions... With each new version, there were some updates to Ninject in order to make it work properly and be easily configurable with Web API mechanism. It's very natural to use Dependency Injection with Web API as it's also based on Controllers same as in any ASP.NET MVC application.

The latest Web Api version could be installed directly from NuGet by running the following command:

PM> Install-Package AspNetWebApi

The current version I've installed is v4.0.20710.0

Previously, there were bunch of specific Ninject NuGet packages dedicated for WebAPI, however these were made for the primary alpha versions, thus the current package you only need to install is the following:

PM> Install-Package Ninject.WebApi.DependencyResolver

This package will install all it's dependent packages:


PM> Install-Package Ninject.WebApi.DependencyResolver
Attempting to resolve dependency 'Ninject.Web.Common (≥'.
Attempting to resolve dependency 'Ninject (≥ && <'.
Attempting to resolve dependency 'WebActivator (≥ 1.5)'.
Attempting to resolve dependency 'Microsoft.Web.Infrastructure (≥'

Once installed, you will get NinjectWebCommon.cs inside App_Start. Open that file and add the following line inside CreateKernel() method right after RegisterServices(kernel);

System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);

Now, you can freely create your dependency injection binding maps and take advantage of DI mechanisms. The way you will use it exactly the same as in ASP.NET MVC... There are many articles and tutorials you can search on web for that.

Happy Coding!



Comments have been disabled for this content.