Session Wrapper in ASP.NET

When using session in ASP.NET without a wrapper class, you may run into "Magic Constant" syndrome. A possible solution to overcome is to use Session Wrapper Class.

While browsing through internet for possible implementation of Session Wrapper in ASP.NET, I found a useful blog by Matt Berther. You can find that blog here.

Taking the concept in Matt's blog further, I implemented Session Wrapper in the following way:

  1. [Serializable]  
  2.   
  3. public class SessionWrapper  
  4. {  
  5.   
  6.     private const string SESSION_WRAPPER_MANAGER_NAME = "SESSION_WRAPPER_MANAGER";  
  7.   
  8.     private SessionWrapper()  
  9.     {  
  10.   
  11.     }  
  12.   
  13.     private static SessionWrapper Instance  
  14.     {  
  15.   
  16.         get  
  17.         {  
  18.   
  19.             SessionWrapper wrapper = (SessionWrapper)HttpContext.Current.Session[SESSION_WRAPPER_MANAGER_NAME];  
  20.   
  21.             if (wrapper == null)  
  22.             {  
  23.   
  24.                 wrapper = new SessionWrapper();  
  25.   
  26.                 HttpContext.Current.Session[SESSION_WRAPPER_MANAGER_NAME] = wrapper;  
  27.   
  28.             }  
  29.   
  30.             return wrapper;  
  31.   
  32.         }  
  33.   
  34.     }  
  35.   
  36.     private string _FirstName  
  37.     {  
  38.   
  39.         get;  
  40.   
  41.         set;  
  42.   
  43.     }  
  44.   
  45.     public static string FirstName  
  46.     {  
  47.   
  48.         get  
  49.         {  
  50.   
  51.             return Instance._FirstName;  
  52.   
  53.         }  
  54.   
  55.         set  
  56.         {  
  57.   
  58.             Instance._FirstName = value;  
  59.   
  60.         }  
  61.   
  62.     }  
  63.   
  64. }  

In this implementation I have taken two properties, one private instance property and one public static property. The private instance property belongs to an instance object. The entire instance object is stored in the Session.

The intention of making Instance property private is that we'll only use it within the class and don't want to expose the instance property.

Advantages of this approach:

  1. Need not define string constants for each and every session variable, hence overcoming possibility of Magic Constant Syndrome.

  2. Simple approach, need not handle session for each and every variable.

  3. Easy to manage and code.