Ninject中的OnePerRequestBehaviour似乎无法正常工作?

6
我一直在我的网页应用程序中使用Ninject作为我的IOC容器。它很棒,我认为它工作得非常好,但是我一直在尝试将一些接口/类注册为OnePerRequestBehavior,但似乎并没有真正使用该行为。代码可以正确运行,但是在我的某个类中,它会从数据库中惰性加载页面信息,一旦加载完成,就不需要再次访问数据库。
我的问题是,惰性加载的属性将在我的第一个请求中加载,在我请求下一页时,将使用相同的类实例。我知道这是因为该类未被重新实例化,并且惰性加载的属性已经设置好了。
此代码位于我的模块类中:
public class NinjectModule : StandardModule
{
    public override void Load()
    {
        Bind<IUnitOfWorkDataStore>().To<HttpContextDataStore>().Using<OnePerRequestBehavior>();


        Bind<CmsService>().ToSelf().Using<OnePerRequestBehavior>();
        Bind<CmsRepository>().ToSelf().Using<OnePerRequestBehavior>();
    }
}

然后在我的 Global.asax 中,它是从 NinjectHttpApplication 继承的,我有以下内容:

        protected override IKernel CreateKernel()
        {
            OnePerRequestModule module = new OnePerRequestModule();
            module.Init(this);

            KernelOptions options = new KernelOptions();
            options.InjectNonPublicMembers = true;

            IKernel kernel = new StandardKernel(options, new NinjectModule());

            return kernel;
        }

第一个调用CmsService的地方是在global.asax文件中的authenticate_request事件中。
protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.Url.AbsoluteUri.Contains(".aspx") &&
                !HttpContext.Current.Request.Url.AbsoluteUri.Contains(".aspx/"))
            {
                CmsService facCMS = HttpKernelFactory.Get<CmsService>();
                ContentPage page = facCMS.GetCurrentPage();

                // DO Logic based on the page being brought back
            }
        }

上述 GetCurrentPage() 代码:
public ContentPage GetCurrentPage()
{
    if (_currentPage != null)
        return _currentPage;

    return GetCurrentPage(_isAdmin);
}

如您所见,如果之前没有设置_currentPage变量,则只会加载一次,这应该是每个请求一次,但是Ninject似乎不会按请求创建CmsService,而是为任意时间创建它。

有人有任何想法,为什么这对我不起作用,或者任何确实有效的示例代码吗?

谢谢

1个回答

9

OnePerRequestModule是一个HttpModule,需要加载到ASP.NET管道中才能工作。如果将其添加到web.config中,则应该可以正常工作:

IIS7:

<system.webServer> 
  <modules>
    <add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/>
  </modules>
</system.webServer>

IIS6:

<system.web>
  <httpModules>
    <add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/>
  </httpModules>
</system.web>

Ninject2(尚未发布)中的OnePerRequest行为得到了极大的改进。


1
非常准确,谢谢。但我猜从创建者那里得到的答案也不会是错误的!Ninject真的很好,我喜欢它。你有没有想过什么时候希望发布Ninject2? - John_

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接