WebApi with Ninject

With WebApi it really sucks that you can’t add its dependencies through IoC like you normally would for any MVC project.  To get it working with WebApi there are two interfaces that you have to implement (IDependencyResolver and IDependencyScope).

The IDependencyScope has two methods that you have to implement “GetService” and “GetServices” both expects a Type and returns an object or a collection of objects.

dependencyScope

Then implement the IDependencyResolver which has one method “BeginScope” where you simply return back a new instance of an implementation of IDependencyScope (above class).

dependencyResolverPNG

Now add a new xxxxConfig class in the App_Start folder with the following code and register it in your Global.asax class

IocPNG

global

References: Web API Dependency Resolver, IDependencyResolver, IDependencyScope



Leave a comment