How to use Ninject with ASP.NET Web API?

烈酒焚心 提交于 2019-11-26 20:39:12

问题


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?


回答1:


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/



回答2:


The current version of Ninject.Web.WebApi, since at least 3.2.1.0, no longer requires anything additional to be added manually. Just add the package and register everything in NinjectWebCommon.cs, as usual.




回答3:


For Web Api 2 you need these nuget packages -

Ninject
Ninject.Web.Common
Ninject.Web.WebApi 
Ninject.Web.Common.WebHost
WebActivatorEx 

And you need to edit NinjectWebCommon.CreateKernel(..)to include

RegisterServices(kernel);
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;

I've written a detailed blog post here - http://NoDogmaBlog.bryanhogan.net/2016/04/web-api-2-and-ninject-how-to-make-them-work-together/ including a full solution to download.




回答4:


The following steps work like a sharm to get Ninject working on an WebAPI project:

  1. Install the Ninject.Web.WebApi NuGet package.
  2. Install the Ninject.Web.WebApi.WebHost NuGet package.
  3. Register your dependencies in the method "RegisterServices" in the file NinjectWebCommon added to the App_Start folder. Like this:

Private static void RegisterServices(IKernel kernel)
{

  kernel.Bind <IFoo>().To <Foo>();

} 


来源:https://stackoverflow.com/questions/14016727/how-to-use-ninject-with-asp-net-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!