簡體   English   中英

帶有Ninject的WebAPI

[英]WebAPI with Ninject

我遇到了麻煩,制作了Ninject和WebAPI.All合作。 我會更具體:
首先,我玩了WebApi.All包,看起來它對我來說很好。
其次,我在Global.asax下一行添加了RegisterRoutes

routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));

所以最終的結果是:


public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

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

}

一切似乎都很好,但是當我試圖將用戶重定向到特定的操作時,例如:

 return RedirectToAction("Index", "Home"); 

瀏覽器中的url是localhost:789/api/contacts?action=Index&controller=Home哪個不好。 我在RegisterRoute划線,現在看起來:


public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );
            routes.Add(new ServiceRoute("api/contacts", new HttpServiceHostFactory(), typeof(ContactsApi)));
            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

        }

現在重定向工作正常,但是當我嘗試訪問我的API動作時,我得到錯誤告訴我Ninject couldn't return controller "api" ,這絕對合乎邏輯,我沒有這樣的控制器。

我確實搜索了一些如何使Ninject與WebApi一起工作的信息,但我找到的所有內容僅適用於MVC4或.Net 4.5。 由於技術問題,我無法將我的項目轉移到新平台,所以我需要為這個版本找到一個可行的解決方案。

這個答案看起來像一個有效的解決方案,但是當我嘗試啟動項目時,我得到編譯器錯誤

CreateInstance = (serviceType, context, request) => kernel.Get(serviceType);

告訴我:

System.Net.Http.HttpRequestMessage is defined in an assembly that is not referenced

以及在裝配中添加refference的一些事情

System.Net.Http, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

我不知道下一步該做什么,我在.NET 4和MVC3上找不到關於ninject和webapi的任何有用信息。 任何幫助,將不勝感激。

以下是我為您編寫的幾個步驟,可以幫助您入門:

  1. 使用Internet模板創建新的ASP.NET MVC 3項目
  2. 安裝以下2個NuGets: Microsoft.AspNet.WebApiNinject.MVC3
  3. 定義一個接口:

     public interface IRepository { string GetData(); } 
  4. 並實施:

     public class InMemoryRepository : IRepository { public string GetData() { return "this is the data"; } } 
  5. 添加API控制器:

     public class ValuesController : ApiController { private readonly IRepository _repo; public ValuesController(IRepository repo) { _repo = repo; } public string Get() { return _repo.GetData(); } } 
  6. Application_Start注冊API路由:

     public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); GlobalConfiguration.Configuration.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } 
  7. 使用Ninject添加自定義Web API依賴關系解析器:

     public class LocalNinjectDependencyResolver : System.Web.Http.Dependencies.IDependencyResolver { private readonly IKernel _kernel; public LocalNinjectDependencyResolver(IKernel kernel) { _kernel = kernel; } public System.Web.Http.Dependencies.IDependencyScope BeginScope() { return this; } public object GetService(Type serviceType) { return _kernel.TryGet(serviceType); } public IEnumerable<object> GetServices(Type serviceType) { try { return _kernel.GetAll(serviceType); } catch (Exception) { return new List<object>(); } } public void Dispose() { } } 
  8. Create方法( ~/App_Start/NinjectWebCommon.cs )中注冊自定義依賴項解析器:

     /// <summary> /// Creates the kernel that will manage your application. /// </summary> /// <returns>The created kernel.</returns> private static IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel); kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); RegisterServices(kernel); GlobalConfiguration.Configuration.DependencyResolver = new LocalNinjectDependencyResolver(kernel); return kernel; } 
  9. RegisterServices方法中配置內核( ~/App_Start/NinjectWebCommon.cs ):

     /// <summary> /// Load your modules or register your services here! /// </summary> /// <param name="kernel">The kernel.</param> private static void RegisterServices(IKernel kernel) { kernel.Bind<IRepository>().To<InMemoryRepository>(); } 
  10. 運行應用程序並導航到/api/values

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM