我一直在我的网页应用程序中使用Ninject作为我的IOC容器。它很棒,我认为它工作得非常好,但是我一直在尝试将一些接口/类注册为OnePerRequestBehavior,但似乎并没有真正使用该行为。代码可以正确运行,但是在我的某个类中,它会从数据库中惰性加载页面信息,一旦加载完成,就不需要再次访问数据库。
我的问题是,惰性加载的属性将在我的第一个请求中加载,在我请求下一页时,将使用相同的类实例。我知道这是因为该类未被重新实例化,并且惰性加载的属性已经设置好了。
此代码位于我的模块类中:
第一个调用CmsService的地方是在global.asax文件中的authenticate_request事件中。
上述 GetCurrentPage() 代码:
我的问题是,惰性加载的属性将在我的第一个请求中加载,在我请求下一页时,将使用相同的类实例。我知道这是因为该类未被重新实例化,并且惰性加载的属性已经设置好了。
此代码位于我的模块类中:
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,而是为任意时间创建它。
有人有任何想法,为什么这对我不起作用,或者任何确实有效的示例代码吗?
谢谢