Asp.net-Mvc-4

HttpContextBase 是如何向 ninject 註冊的?我沒有明確綁定它

  • July 17, 2015

我在我的 NinjectWebCommon.RegisterServices 方法中為 HttpContextBase 創建了一個綁定,但是當我嘗試在我的控制器或服務中引用它時,我收到一條錯誤消息。

這是綁定:

kernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current)).InRequestScope();

這是錯誤消息:

Error activating HttpContextBase
More than one matching bindings are available.
Activation path:
2) Injection of dependency HttpContextBase into parameter abase of constructor of type HomeController
1) Request for HomeController

Suggestions:
1) Ensure that you have defined a binding for HttpContextBase only once.

如果我刪除綁定,那麼它似乎做了我想要的(解析為 HttpContextWrapper),但我想知道它是如何註冊的?

但我想知道這是如何註冊的?

查看原始碼,MvcModule.cs您的問題將立即得到解答:

this.Kernel.Bind<HttpContext>().ToMethod(ctx => HttpContext.Current).InTransientScope();
this.Kernel.Bind<HttpContextBase>().ToMethod(ctx => new HttpContextWrapper(HttpContext.Current)).InTransientScope();

我看到 Ninject.Web.Common v3.2.3.0 註冊的綁定

如果您嘗試在單元測試中模擬綁定,則必須先將其刪除,如下所示:

// WebCommonNinjectModule loads HttpContextBase. We need to remove it
var httpContextBaseBinding = kernel.GetBindings(typeof(System.Web.HttpContextBase)).FirstOrDefault();
kernel.RemoveBinding(httpContextBaseBinding);
kernel.Bind<System.Web.HttpContextBase>().ToMethod(m => httpContextBaseMock.Object);

引用自:https://stackoverflow.com/questions/16962722