出于某种原因,当我在我的 MVC 4 应用程序中使用 NinjectHttpModule
时,Ninject 正在创建我的对象的一个额外实例。
如果我使用 NinjectHttpModule
(Ninject.MVC3 默认值)但实际上没有任何需要构造函数注入(inject)的 IHttpModule
类,它工作正常。但是,一旦我创建了一个实现 IHttpModule
并且需要构造函数注入(inject)的类,Ninject 就会出于某种原因创建我的对象的两个实例。
我在被复制的类中添加了一些跟踪代码以验证它是否被复制。每次创建实例时,静态计数变量都会递增:
namespace Trigger.Events
{
public class TriggerEventRegistry : ITriggerRegistry
{
private static int count;
public TriggerEventRegistry()
{
TriggerEventRegistry.count++;
}
}
}
这是我的 IHttpModule
:
namespace TriggerDevelopment.ApplicationTriggers
{
public class RegisterTriggerComponentsHttpModule : IHttpModule
{
ITriggerEventRegistry eventRegistry;
public RegisterTriggerComponentsHttpModule(ITriggerEventRegistry eventRegistry)
{
this.eventRegistry = eventRegistry;
}
}
....
}
当 TriggerEventRegistry
被注入(inject)我的 Controller 时(在同一个请求上),TriggerEventRegistry.count
等于 2
。如果我在 RegisterTriggerComponentsHttpModule
上注释掉构造函数,则 TriggerEventRegistry.count
的值等于 1
(这是应该的,因为应该只有一个实例/请求)。
绑定(bind)代码如下:
Bind<ITriggerEventRegistry>().To<TriggerEventRegistry>().InRequestScope();
如有任何帮助,我们将不胜感激!
注意
我什至使用 curl 向我的应用发出请求,以避免浏览器发出多个 HTTP 请求以查找 Assets 、网站图标或类似内容。仍然没有快乐。
更新
经过进一步调查,我还发现 RegisterTriggerComponentsHttpModule
的构造器和 Init
方法被调用了两次。
最佳答案
它会根据请求多次调用您的 HttpModule。例如,大多数 Web 浏览器至少提交两个请求,页面请求和网站图标请求。尝试向页面添加类似图片的内容,看看是否收到三个请求...
关于c# - Ninject 在使用 NinjectHttpModule 时创建一个额外的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15716439/