MVC3, Unity Framework and Perl Lifetime Manager Issue

In a simple word, I'm trying to create a Lifetime manager for the Unity framework using the Http Session in my MVC3 project. My sample lifecycle manager implementation:

public class UnityPerSessionLifetimeManager : LifetimeManager { private string sessionKey; private HttpContext ctx; public UnityPerSessionLifetimeManager(string sessionKey) { this.sessionKey = sessionKey; this.ctx = HttpContext.Current; } public override object GetValue() { return this.ctx.Session[this.sessionKey]; } public override void RemoveValue() { this.ctx.Items.Remove(this.sessionKey); } public override void SetValue(object newValue) { this.ctx.Session[this.sessionKey] = newValue; } } 

In my global.asax.cs, I replaced the factory default controller with my own UnityControllerFactory

  public class UnityControllerFactory : DefaultControllerFactory { private IUnityContainer container; public UnityControllerFactory(IUnityContainer container) { this.container = container; this.RegisterServices(); } protected override IController GetControllerInstance(RequestContext context, Type controllerType) { if (controllerType != null) { return this.container.Resolve(controllerType) as IController; } return null; } private void RegisterServices() { this.container.RegisterType<IMyType, MyImpl>(new UnityPerSessionLifetimeManager("SomeKey")); } } } 

I set breakpoints for each function of the UnityPerSessionLifetimeManager class, I noticed that when the factory controller tries to solve the dependencies of my controller, the HttpContext.Session is actually null, so the code is not obtained from the session or saved to the session.

Any idea why the session at this stage is zero?

+4
source share
1 answer

My mistake, I have to change the code of the UnityPerSessionLifetimeManager class to be

 public class UnityPerSessionLifetimeManager : LifetimeManager { private string sessionKey; public UnityPerSessionLifetimeManager(string sessionKey) { this.sessionKey = sessionKey; } public override object GetValue() { return HttpContext.Current.Session[this.sessionKey]; } public override void RemoveValue() { HttpContext.Current.Session.Remove(this.sessionKey); } public override void SetValue(object newValue) { HttpContext.Current.Session[this.sessionKey] = newValue; } } 

because when the constructor was called for the register type, the session state is not ready yet, and I have already assigned the http context of this time to a variable. But in later Get / Set functions, the session state is ready.

+4
source

Source: https://habr.com/ru/post/1395251/


All Articles