Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Ninject with ASP.NET Web API?

In MVC I simply make the class NinjectControllerFactory that implements DefaultControllerFactory interface then do some bindings in it. at last in Global I run it:

ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

But what about using Ninject in ASP.NET Web API? there are some information on the web but are out dated and for pre-released versions.

Is there a straightforward way for this problem?

like image 583
Blazi Avatar asked Dec 24 '12 03:12

Blazi


People also ask

What is NInject Web API?

NInject is a popular IOC container that can be used to inject dependencies in your WebAPI controllers easily. IDG. Dependency injection is a software design pattern that helps you to build pluggable implementations in your application using loosely coupled, testable components.

Where do I register dependency injection in Web API?

Set the dependency resolver on the DependencyResolver property of the global HttpConfiguration object. The following code registers the IProductRepository interface with Unity and then creates a UnityResolver . public static void Register(HttpConfiguration config) { var container = new UnityContainer(); container.

What is the use of NInject?

Ninject is a lightweight dependency injection framework for . NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner.


1 Answers

The reason a lot of the articles are old is because the approach hasn't changed since June 2012 (RC released May 31st). You need to add the Ninject MVC3 Nuget package, then implement 'IDepenencyResolver' and then register your implementation.

The best two walk-thoughs are:

  1. http://www.strathweb.com/2012/05/using-ninject-with-the-latest-asp-net-web-api-source/
  2. http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api/
like image 165
Mark Jones Avatar answered Oct 14 '22 18:10

Mark Jones