Using ASP.NET Session for Lifetime Management (Unity) Using ASP.NET Session for Lifetime Management (Unity) asp.net asp.net

Using ASP.NET Session for Lifetime Management (Unity)


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.


Why not use the cache object instead...then you can use it both from win and web. Like this:

    IUnityContainer container= HttpRuntime.Cache.Get("Unity") as IUnityContainer;    if (container == null)    {        container= // init container        HttpRuntime.Cache.Add("Unity",            container,            null,            Cache.NoAbsoluteExpiration,            Cache.NoSlidingExpiration,            CacheItemPriority.NotRemovable,            null);    }    // return container or something

HttpRuntime.Cache will work both in win and web


I would think that you need two services that you expose through unity (or one service that does both actions).

Instead of storing the user object, store an interface implementation which exposes a method/property that will get the user object for you. In the ASP.NET case, you retrieve the user from the session. In the WinForm solution (or whatever), you can get it from the executing thread.

You would also have a set method/property as well, which you would use to set the user.