wayne on March 13, 2008
As I build applications there are times where I need to throw something into session state. When I do so, I hate to have all the session state calls spread throughout the code files, so what I do is define a single class that wrappers each session state item. This allows me to keep track of all session state items the application is using.
Here is a sample of the SessionManager class:
/// <summary>
/// Provides an organized means to manage session state items
/// </summary>
public static class SessionManager
{
/// <summary>
/// The currently logged in user object
/// </summary>
public static EPModel.User UserObj
{
get
{
if (HttpContext.Current.Session["UserObj"] != null)
return ((User)HttpContext.Current.Session["UserObj"]);
else
return null;
}
set { HttpContext.Current.Session["UserObj"] = value; }
}
/// <summary>
/// Indicates if the Program menu should be shown or not
/// </summary>
public static bool SomeValue
{
get
{
if (HttpContext.Current.Session["SomeValue"] == null)
return false;
else
return (bool)HttpContext.Current.Session["SomeValue"];
}
set { HttpContext.Current.Session["SomeValue"] = value; }
}
}
The class contains two public properties, one for a generic object, the other for a boolean value. The class is made static so that no instantiation is required.
As I need to create session state items during development, I simply pop it right in here and I'm good to go. No more will I hunt for items being thrown into session state across an entire app, all I need to do is rename the class, and viola! The .Net compiler will mark them for me. The alternative is performing a Find All which is fine also, just a matter of preference really.
The value from handling your session variables this way is that it allows you to control the output to the callers. I test for nulls and return null when necessary or return a default value, depends on the type and usage within the application, but I standardize it for the whole application. I don't have to perform checks at each call, they are handled for me here as well as the casting to the appropriate type.
I would love to hear some feedback on this since there may be better ways to manage session state within an ASP.Net application, but this is currently my favorite way to keep a grip on session state items.