Strongly Typed .NET Session Pattern

When working in a strongly typed language like C#, I prefer to avoid being “stringly typed“. Thus I typically wrap .NET’s session object with a custom wrapper. This offers three core benefits:

  1. Compile-time error checking to protect from typos and assigning improper types
  2. Find all references support makes it easy to see all uses of a given session value. This aids refactoring and helps protect from accidentally placing the same data in multiple session variables.
  3. Intellisense support in the IDE saves typing and avoids hunting around for the desired magic string.

Here’s a quick example implementation that wraps two session values.

/// <summary>
/// Wraps .NET session so that calls can be strongly typed and intellisense supported.
/// </summary>
public class SessionHelper : System.Web.SessionState.IRequiresSessionState
	public static int UserID
		get { return HttpContext.Current.Session["UserID"] == null ? 0 : Convert.ToInt32(HttpContext.Current.Session["UserID"]); } 
		set { HttpContext.Current.Session["UserID"] = value; }

	public static string UserName
		get { return HttpContext.Current.Session["UserName"].ToString(); }
		set { HttpContext.Current.Session["UserName"] = value; }

This example is simple for readability, but it would be wise to add a check in the UserID setter to assure an integer is being passed. This would assure only appropriate types can be stored in a given session variable.

Accessing a UserName from session is safe and simple:

//Get username from session
string username = SessionHelper.Username;

Of course, if you’re using dependency injection, then the statics should be replaced with instance variables and an interface should be defined to support mocking.

One reply on “Strongly Typed .NET Session Pattern”

Comments are closed.