[Web API] Dependency Injection with Ninject

There are many Dependency Injection libraries for ASP.NET MVC or Web API. Ninject is one of them. Ninject is optimized for MVC but you can use it for Web API with a minor adjustment.

 

1. Installing Ninject

Ninject can be installed via NuGet packages so installation is pretty easy.

You can install the general “Ninject” package and set up the project but if you use MVC, you can install the “Ninject.MVC” package. It will install “Ninject” and “Ninject.Web.Common” packages as well and make necessary changes in the MVC project.

At the time of writing,  “Ninject.MVC3” is the latest but it works with MVC4 without any problems.

 

2. Binding Types

In the “App_Start” folder, the static “NinjectWebCommon” class is created for you. Only thing you need to do is to add binding mappings in the “RegisterServices()” method.

private static void RegisterServices(IKernel kernel)
{
  kernel.Bind<IProductRepository>().To<ProductRepository>();
}

That’s all for MVC projects.

 

3. Web API

Unfortunately, Ninject dependency inject does not work for Web API controllers.

You need 2 tasks to make it work:

  • Install “WebApiContrib.IoC.Ninject” package via NuGET
  • Add the following code in the “CreateKernel()” method
private static IKernel CreateKernel()
{
  var kernel = new StandardKernel();
  kernel.Bind<Func<IKernel>>()
    .ToMethod(ctx => () => new Bootstrapper().Kernel);
  kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

  // Support Web API
  System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver
    = new WebApiContrib.IoC.Ninject.NinjectResolver(kernel);

  RegisterServices(kernel);
  return kernel;
}

One thought on “[Web API] Dependency Injection with Ninject

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s