Using ASP.NET Session for Lifetime Management (Unity)

前端 未结 7 2087
猫巷女王i
猫巷女王i 2020-12-10 11:59

I am considering using Unity to manage the lifetime of a custom user class instance. I am planning on extending the LifetimeManager with a custom ASP.NET session manager.

7条回答
  •  一向
    一向 (楼主)
    2020-12-10 12:30

    You'd get the best bang with Unity when used with ASP.Net MVC rather than the plain old ASP.Net project. ASP.Net MVC allows you to use a container like Unity to manage the user objects, controllers, models, etc. If possible, use MVC rather than ASP.net web forms for your projects.

    If I understand your question correctly, you would want to use Unity to maintain the lifetime of the object to per session. You need to implement a SessionLifetimeManager that extends LifetimeManager. The code is pretty simple and goes along these lines:

    public class SessionLifetimeManager : LifetimeManager
    {
        private string _key = Guid.NewGuid().ToString();
    
        public override object GetValue()
        {
              return HttpContext.Current.Session[_key];
        }
    
        public override void SetValue(object value)
        {
              HttpContext.Current.Session[_key] = value;
        }
    
        public override void RemoveValue()
        {
              HttpContext.Current.Session.Remove(_key);
        }
    }
    

    You could also write a similar one for PerWebRequest lifetime management.

提交回复
热议问题