將 Ninject 與 Asp.NET Web API Beta ApiController 一起使用
我被困住了。我使用此處概述的方法用於 wcf web api p6 Ninject 與 WCF Web API Preview 5 一起使用,但是與測試版中的 mvc 實現有很大不同。這裡有一篇很好的文章http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver討論了建構自己的自定義依賴解析器,但是我想使用與我的 mvc 視圖控制器相同的實現…例如 Ninject。我也根據文章中的 IoC Unity 範例嘗試了一些事情,但還沒有成功。任何為我指明正確方向的幫助將不勝感激。我也將繼續自己探勘。提前致謝!
這就是我所在的地方。我使用 WebActivator 來引導程式碼,但後來我把它放到 Application_Start() 中,只是為了擺脫等式。
protected void Application_Start() { var kernel = new StandardKernel(new MyNinjectModule()); GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new NinjectDependencyResolver(kernel)); }並且收到以下錯誤:
Ninject.Web.Mvc.NinjectDependencyResolver 類型似乎沒有實現 Microsoft.Practices.ServiceLocation.IServiceLocator。
參數名稱:commonServiceLocator找到解決方案
也許有/將會有一種更優雅的方式,但這現在對我有用。我也在這裡添加了我的自定義消息處理程序。
[assembly: WebActivator.PreApplicationStartMethod(typeof(MyApp.AppStart.ApiBootstrapper), "Start")] namespace MyApp.AppStart { public class ApiBootstrapper { public static void Start() { var kernel = new StandardKernel(new MyNinjectModule()); var resolver = new NinjectDependencyResolver(kernel); GlobalConfiguration.Configuration.ServiceResolver.SetResolver(resolver.GetService, resolver.GetServices); GlobalConfiguration.Configuration.MessageHandlers.Add(new ApiAuthHandler()); } } }
我從未使用過 WebAPI,但由於 IDependencyResolver 的語義與 MVC3 中的語義完全相同,因此您應該能夠使用相同的實現:https ://github.com/ninject/ninject.web.mvc/blob/master /mvc3/src/Ninject.Web.Mvc/NinjectDependencyResolver.cs
更新:Ninject.Web.WebAPi 擴展增加了對 ApiControllers 的支持
我找到了答案並用解決方案更新了我上面的問題。解決方案本身或多或少出現在Using the Web API Dependency Resolver文章中,我只需要繼續調整 ninject。這兩個答案都幫助我迅速縮小了範圍,感謝@Remo 和@James。