Object Oriented Programming Patterns for Geeks

A Web Session Singleton

You could consider this singleton to be the web application friendly version of the ThreadSingleton (Well... almost).  It lives inside the HttpContext Session dictionary as a standard session serialized object instead of staying in state against a specific thread and ss usual for session data it is (de)serialized against which ever session serialisation source you are using

In more complicated incarnations this form of class can allow all sorts of extensions to your web session model.  Using the various facilities available in .NET for instance you can engineer and associate all forms of models directly against the session data in a much more OOP friendly manner.

This is my prefered way of working with session stated data.  I sometimes wonder why so many other people don't themselves...

[Serializable]
public sealed class SessionSingleton
{
    private const string SESSION_KEY 
                        
= "MySession_3BC433AB-3925-4bee-9EDD-7F874D241AD0"; /// <summary> /// Some basic instance data. /// </summary> private string _SomeInstanceData; /// <summary> /// Gets or sets some instance data. /// </summary> /// <value>Some instance data.</value> public string SomeInstanceData { get { return this._SomeInstanceData; } set { this._SomeInstanceData = value; } } /// <summary> /// Initializes a new instance of the <see cref="SessionSingleton"/> class. /// This is privately invoked /// </summary> private SessionSingleton() { this._SomeInstanceData = "Hi!"; } /// <summary> /// Gets the singleton. /// </summary> /// <value>The singleton.</value> public static SessionSingleton Session { get { // double check locking... if( HttpContext.Current.Session[SESSION_KEY] == null ) lock( HttpContext.Current.Session.SyncRoot ) if( HttpContext.Current.Session[SESSION_KEY] == null ) HttpContext.Current.Session[SESSION_KEY] =
                                                            
new SessionSingleton(); return HttpContext.Current.Session[SESSION_KEY] as SessionSingleton; } } }