AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=70&pId=-1
Session Based Singleton Object
page
by Robert Boedigheimer
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 32474/ 56

Background

The Session object in ASP.Net can be used to store information that is specific to an individual user of the site. The Session is indexed by a key name, and when it is used directly in such a manner it can lead to a large number of individual session names. An alternative approach is to instead create a singleton object to group related items and store that object with a given key name. The "singleton" is a common design pattern that specifies how to ensure that only a single instance of a class exists at any time.

Advantages of Singleton Session Objects

  • Grouping of session items for organization purposes
  • Especially useful for a series of pages on a transient process such as registration on a site. Once the process is complete the object can be cleared from the session so the memory can be reclaimed (better use of server resources)
  • Impact analysis of changes to session information is much easier
  • Identify areas of the site that are misusing information (much clearer than just using the name of the variable to determine if it is appropriate to use)
  • Intellisense for property names and types once access the object

Disadvantages of Singleton Session Objects

  • More difficult to see the number of individual items in session
  • ASP.Net Trace results does not show the values inside the object
  • Performance degradation when using out of process session state storage (affects serialization)

Implementation

The first implementation step is to create a class file that represents the logical grouping of items that should be stored together in the single object. The following is a sample class that demonstrates the technique:
public class singleton
{
  //Name that will be used as key for Session object
  private const string SESSION_SINGLETON = "SINGLETON";

  //Variables to store the data (used to be individual
  // session key/value pairs)
  string lastName = "";
  string firstName = "";

  public string LastName
  {
    get
    {
      return lastName;
    }
    set
    {
      lastName = value;
    }
  }

  public string FirstName
  {
    get
    {
      return firstName;
    }
    set
    {
      firstName = value;
    }
  }

  //Private constructor so cannot create an instance
  // without using the correct method.  This is 
  // this is critical to properly implementing
  // as a singleton object, objects of this
  // class cannot be created from outside this
  // class
  private singleton()
  {
  }

  //Create as a static method so this can be called using
  // just the class name (no object instance is required).
  // It simplifies other code because it will always return
  // the single instance of this class, either newly created
  // or from the session
  public static singleton GetCurrentSingleton()
  {
    singleton oSingleton;

    if (null == System.Web.HttpContext.Current.Session[SESSION_SINGLETON])
    {
      //No current session object exists, use private constructor to 
      // create an instance, place it into the session
      oSingleton = new singleton();
      System.Web.HttpContext.Current.Session[SESSION_SINGLETON] = oSingleton;
    }
    else
    {
      //Retrieve the already instance that was already created
      oSingleton = (singleton)System.Web.HttpContext.Current.Session[SESSION_SINGLETON];
    }

    //Return the single instance of this class that was stored in the session
    return oSingleton;
  }
}

A page that wants to use this object simply does the following:
    singleton oSingleton = singleton.GetCurrentSingleton();
    oSingleton.FirstName = "Robert";
    oSingleton.LastName = "Boedigheimer";

Typically this technique will store many more variables in the given class or will be used for a series of web pages that perform a process. Another advantage of using this for a process on a web site is that all of the memory required for the session variables can be cleared out by simply removing the reference to the singleton object. The class can implement a method that clients can use to clear the reference, it can be named Dispose() to follow the typical .Net pattern when a class provides a way to cleanup:
		
  public static void Dispose()
  {
    //Cleanup this object so that GC can reclaim space
    System.Web.HttpContext.Current.Session.Remove(SESSION_SINGLETON);
  }

Conclusion

There are many advantages to using singleton objects stored in the Session object rather than using individual session keys for storing information. It is useful for objects that are meant to exist for the entire session (grouping logical items, impact analysis, intellisense, etc) and especially for objects that are really only needed for a period of time on a web site until the user completes a particular process (much easier to identify misuse of variables and to conserve resources when the process is completed but the session will continue).

Send comments or questions to robertb@aspalliance.com.


©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-11-21 5:41:37 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search