Ninject for Asp.net Web API

I got this error when using Ninject with a web API, but it works with an MVC controller:

Type 'App.Web.Controllers.ProductController' does not have a default constructor 

NinjectControllerFactory:

 public class NinjectControllerFactory : DefaultControllerFactory { private IKernel ninjectKernel; public NinjectControllerFactory() { ninjectKernel = new StandardKernel(); AddBindings(); } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType); } public void AddBindings() { ninjectKernel.Bind<IProductRepository>().To<EFProductRepository>(); } } 

Global.asax.cs:

 BundleConfig.RegisterBundles(BundleTable.Bundles); ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory()); 

ProductController:

  public class ProductController : ApiController { private IProductRepository repository; public ProductController(IProductRepository ProducteRepository) { this.repository = ProductRepository; } public IEnumerable<Product> GetAllProducts() { return repository.Products.AsEnumerable(); } } 
+4
source share
3 answers

You have exceeded DefaultControllerFactory . But this is used to instantiate ASP.NET MVC controllers (one of which is based on System.Web.Mvc.Controller ). It has nothing to do with ASP.NET Web API controllers (those related to System.Web.Http.ApiController ).

So basically what you did here is dependency injection in ASP.NET MVC. If you want to use this for the web API, you can take a look at the following guides:

+2
source

You should use the latest Ninject Web API package that already solves these problems. See here: http://nuget.org/packages/Ninject.Web.WebApi.WebHost/

+2
source

You need to set the DependencyResolver property for the HttpConfiguration . What have you done for ASP.NET MVC, not ASP.NET Web API.

So, get the NuGet package and install DependencyResolver:

 var kernel = new StandardKernel(); // use kernel to register your dependencies var dependencyResolver = new NInjectResolver(kernel); config.DependencyResolver = dependencyResolver; // config is an instance of HttpConfiguration based on your hosting scenario 
+1
source

Source: https://habr.com/ru/post/1492449/


All Articles