MVC3, Unity Framework and Per Session Lifetime Man

2020-03-24 18:53发布

问题:

In a simple word I try to create Lifetime manager for Unity framework by using Http Session in my MVC3 project. My sample implementation of lifetime manager is:

    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 default controller factory 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 on each function of UnityPerSessionLifetimeManager class, I noticed that when controller factory tries to solve dependencies of my controller, the HttpContext.Session is actually null, so the code fails retrieve from session or save to session.

Any idea why session is null at this stage?

回答1:

My mistake, I should change code of 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 to register type, session state is not ready yet and I already assigned http context of that time to a variable. But in later Get/Set functions session state is ready.