Thursday, April 3, 2008

Singleton Session Manager

A long while back I found a post on CodeProject that wrapped session management into a facade pattern. At the time, I was fighting Session overload from developers who were moving from the classic asp world to .Net. I wanted an easy, centralized, type-safe way to manage sessions.

Preferably, I would have done away with sessions, but every time I thought I had figured out a way to do so, some situation arose that required the use of a session variable. So finally I bit the bullet and agreed but with some stipulations.

The following code was my stipulation. All session information had to go through this class.

[Serializable()]
class SiteContext
{

private const string SITE_CONTEXT = "ApplicationContext";

private SiteContext()
{

}

#region SiteContext Properties
public static SiteContext Current
{
get
{
SiteContext context;
if(HttpContext.Current.Session[SITE_CONTEXT] == null)
{
context = new SiteContext();
HttpContext.Current.Session[SITE_CONTEXT] = context;
}
else
{
context = (SiteContext)HttpContext.Current.Session[SITE_CONTEXT];
}

return context;
}
}

#endregion

#region SiteContext Fields

private int m_StartMonth;
public int StartMonth
{
get { return m_StartMonth;}
set { m_StartMonth = value;}
}

#endregion
}


Then in my code I could do this...

SiteContext.Current.StartMonth = 1 //Adds a value to session state

and

int Month = SiteContext.Current.StartMonth //Retrieves the value from session state

Nothing too fancy here, but it works great for centralizing session variables.

I would love to give the original poster credit for this code, but I couldn't find it. If anyone knows please send me the original post and I'll be glad to include it.