如何在ASP.NET Web API中使用Ninject?

Bla*_*azi 19 asp.net-mvc dependency-injection ninject asp.net-web-api

在MVC中,我只是创建NinjectControllerFactory实现DefaultControllerFactory接口的类,然后在其中执行一些绑定.最后在Global我运行它:

ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
Run Code Online (Sandbox Code Playgroud)

但是在ASP.NET Web API中使用Ninject呢?网上有一些信息,但已过时和预发布版本.

这个问题有直接的方法吗?

Mar*_*nes 19

许多文章陈旧的原因是因为这种方法自2012年6月以来没有改变(RC于5月31日发布).您需要添加Ninject MVC3 Nuget包,然后实现'IDepenencyResolver'然后注册您的实现.

最好的两个步行道是:

  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/


Chr*_*att 6

Ninject.Web.WebApi的当前版本,至少从3.2.1.0开始,不再需要任何额外的手动添加.只需添加包并像往常一样在NinjectWebCommon.cs中注册所有内容.

  • 您还需要按照http://stackoverflow.com/questions/22768721/parameterless-constructor-error-with-ninject-bindings-in-net-web-api-2-1上的说明进行操作. (3认同)

Bry*_*yan 5

对于Web Api 2,您需要以下nuget软件包-

Ninject
Ninject.Web.Common
Ninject.Web.WebApi 
Ninject.Web.Common.WebHost
WebActivatorEx 
Run Code Online (Sandbox Code Playgroud)

您需要进行修改NinjectWebCommon.CreateKernel(..)以包括

RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
Run Code Online (Sandbox Code Playgroud)

我在这里写了详细的博客文章-http://NoDogmaBlog.bryanhogan.net/2016/04/web-api-2-and-ninject-how-to-make-them-work-together//包括完整的解决方案去下载。