Strongly-Typed Session in ASP.NET
Session state is a very useful tool for an ASP.NET developer. I use the Session object in every project. I use it to store information related to the current user that I need quick access to throughout their visit. It's important not to overuse the Session object but rather to store quick bits of information that need to persist over a single, or multiple, post-backs.
The most painful part of using the Session object built-in to the ASP.NET framework is the error prone nature of getting and setting variables inside of the Session object. The common usage of getting something out of Session looks like this:
Product product = Session["MyProduct"] as Product;
Sure, it's simple enough and makes sense. However, there is the potential to forget the name of the object you'd like to retrieve. Wouldn't it be nice if the Session was a strongly-typed object that wouldn't allow for this mistake?
In various projects I've been using what I call the SessionWrapper. I can't take credit for the name or the idea, as it was something a past co-worker of mine opened my eyes to. However, his implementation was different than mine in that you simply stored the SessionWrapper object itself in Session and accessed it in your pages. The usage looked like this:
SessionWrapper sessionWrapper = Session["SessionWrapper"] as SessionWrapper; sessionWrapper.Product = new Product();
I wanted to get away from touching the Session object in my presentation code. Why couldn't I simply say:
SessionWrapper.Product = new Product();
With this goal, my implementation of the SessionWrapper was created. The key is using the HttpContext to interact with the Session object while not being required to inherit the Page class. Doing this allows us to access the Session object in a static manner, creating the usage scenario we desire. I've included a full Visual Studio 2008 solution at the bottom of this post. Make sure you check that out. Here's the code for the SessionWrapper class:
using System; using System.Web; namespace SessionWrapperExample { public static class SessionWrapper { public static Product Product { get { if (null != HttpContext.Current.Session["SessionWrapperProduct"]) return HttpContext.Current.Session["SessionWrapperProduct"] as Product; else return null; } set { HttpContext.Current.Session["SessionWrapperProduct"] = value; } } } }