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:
- [Serializable]
-
- public class SessionWrapper
- {
-
- private const string SESSION_WRAPPER_MANAGER_NAME = "SESSION_WRAPPER_MANAGER";
-
- private SessionWrapper()
- {
-
- }
-
- private static SessionWrapper Instance
- {
-
- get
- {
-
- SessionWrapper wrapper = (SessionWrapper)HttpContext.Current.Session[SESSION_WRAPPER_MANAGER_NAME];
-
- if (wrapper == null)
- {
-
- wrapper = new SessionWrapper();
-
- HttpContext.Current.Session[SESSION_WRAPPER_MANAGER_NAME] = wrapper;
-
- }
-
- return wrapper;
-
- }
-
- }
-
- private string _FirstName
- {
-
- get;
-
- set;
-
- }
-
- public static string FirstName
- {
-
- get
- {
-
- return Instance._FirstName;
-
- }
-
- set
- {
-
- Instance._FirstName = value;
-
- }
-
- }
-
- }
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:
- Need not define string constants for each and every session variable, hence overcoming possibility of Magic Constant Syndrome.
- Simple approach, need not handle session for each and every variable.
- Easy to manage and code.