I am using Ninject as my IOC in my web application. This is great, and I think it works very well, however I am trying to register some interfaces / classes as OnePerRequestBehaviour, but it does not seem to use the behavior. The code works correctly, but in one of my classes it lazily loads page information from the database, and then, once it has been loaded, it does not need to be hit on the database.
My problem is that a lazily loaded property will load in my first request, when I then ask the next page to use the same instance of the class. The reason I know this is because the class is not created again, and the lazy loading property is already set.
This code is in my module class:
public class NinjectModule : StandardModule { public override void Load() { Bind<IUnitOfWorkDataStore>().To<HttpContextDataStore>().Using<OnePerRequestBehavior>(); Bind<CmsService>().ToSelf().Using<OnePerRequestBehavior>(); Bind<CmsRepository>().ToSelf().Using<OnePerRequestBehavior>(); } }
Then, inside my Global.asax, which inherits from NinjectHttpApplication, I have the following:
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; }
The first call made to CmsService is also in the global.asax file on 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();
The above code is GetCurrentPage ():
public ContentPage GetCurrentPage() { if (_currentPage != null) return _currentPage; return GetCurrentPage(_isAdmin); }
Since you can see that the _currentPage variable is only loaded if it has not been set earlier, which should be specified for each request, however, Ninject does not seem to create a CmsService for each request, it seems to create it for abritrary amount of time.
Does Deos anyone know why this does not work for me, or any sample code where it definitely works?
thanks