9

我在我的 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),但我想知道它是如何注册的?

4

2 回答 2

21

但我想知道这是如何注册的?

查看源代码,MvcModule.cs您的问题将立即得到解答:

this.Kernel.Bind<HttpContext>().ToMethod(ctx => HttpContext.Current).InTransientScope();
this.Kernel.Bind<HttpContextBase>().ToMethod(ctx => new HttpContextWrapper(HttpContext.Current)).InTransientScope();
于 2013-06-06T14:43:26.447 回答
3

我看到 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);
于 2015-07-17T02:23:27.030 回答