Monthly Archives: October 2012

ASP.Net Web API and Ninject

For the third time I’m using the new Web API in one of my projects and again I hit the wall when it was time to hook up to mu DI framework of choice: Ninject. So this time I’m documenting it here, hopefully that will make me remember it going forward.

To make DI work with Web API there are three steps to perform:

  1. Create two classes: NinjectDependencyScope and NinjectDependencyResolver
    I used the code from Peter Provosts blog.
  2. Hook up the new classes in NinjectWebCommon:
    GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
  3. Create bindings

Fairly easy stuff if you just know how and obviously Peter knew how! There is one caveat though: the NinjectDependencyResolver class also exists in the Ninject.Web.Mvc namespace! This one inherits from IDependencyResolver and we want it to inherit from IDependencyScope. It won’t compile if you reference the wrong class though, so not a big problem really.