Session Based Singleton Object
page 1 of 1
Published: 08 Oct 2003
Unedited - Community Contributed
Abstract
Use singleton objects stored in the Session object to organize and cleanup session based information.
by Robert Boedigheimer
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 22865/ 47

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.


User Comments

Title: Session lost randomly   
Name: siteslayer
Date: 2012-08-06 7:27:03 AM
Comment:
Hi, Robert thanks for your reply. I have sent you a mail containing details of the problem.

Thanks & Regards
Title: Re: Sitealyer   
Name: Robert Boedigheimer
Date: 2012-08-04 9:48:24 AM
Comment:
The could be many reasons why you are losing your session. The solution isn't changing anything about how your session is maintained, so I think the occurrences of loss is not related to the technique per se. The most common causes of (in process) session loss are timeouts, switching physical servers in a web farm, changing files (bin folder, web.config, etc). If you can email me at robertb@aspalliance.com we can discuss how to troubleshoot what might be happening.
Title: Session Lost Randomly   
Name: Siteslayer
Date: 2012-08-04 5:52:11 AM
Comment:
Hi, we have implemented this in our asp.net 3.5 Application. Although it has helped us to keep the code clean & Simple but on the other hand we are experiencing Random session loss. The client is complaining that the users loose their sessions randomly and have to reentered data after logging in again.

Any thoughts?
Title: Gracias   
Name: Jhohan25
Date: 2011-08-11 11:39:14 AM
Comment:
Mil Gracias este codigo es una maravilla para evitar basura en mis variables globales, creando una variable global para cada usuario.

Mil Gracias.
Title: Usefull   
Name: Edu
Date: 2011-05-19 11:36:51 AM
Comment:
Usefull for my project too


Thanks
Title: Fix to the null System.Web.HttpContext.Current.Session   
Name: Judith Barnard
Date: 2010-09-02 9:05:52 AM
Comment:
For those have problems with "Object reference not set to an instance of the object" in
if (null == System.Web.HttpContext.Current.Session[SESSION_SINGLETON]) then make sure this class implements : IHttpHandler, IRequiresSessionState
Title: Great Post=)   
Name: John Doherty
Date: 2010-07-20 9:09:22 AM
Comment:
I agree this is not a "classic" singleton, but within the stateless environment of Http it is a singleton in the sense that it ensures you only ever have one SESSION instance of an object.

This approach also helps boost performance because you’re removing the need to cast many different session variables.

It also helps deliver cleaner code and is easier to debug given that all your session objects are strongly typed and accessible from one static class.

I personally find this very useful, thank you Robert!
Title: reference error   
Name: becavas
Date: 2010-05-24 10:07:36 AM
Comment:
hi, I have a error :

"Object reference not set to an instance of the object"

this error in the line :
if (null == System.Web.HttpContext.Current.Session[SESSION_SINGLETON])
Title: Thanks   
Name: Maarten
Date: 2009-04-07 10:13:27 AM
Comment:
Exactly what I wanted! Thnx :)
Title: Thanks   
Name: Matt
Date: 2008-07-30 12:09:36 PM
Comment:
Wow, this solved a major problem with session objects for us. Thanks for the help. Why are we arguing about whether this is a true "singleton" class? It makes for a very clean way of handling objects within a session in a singleton like manner.
Title: Please don't confuse this with the singleton   
Name: Dave
Date: 2007-06-06 3:10:53 AM
Comment:
This has nothing to do with the Singleton pattern. It is merely a wrapper around accessing the Session for a user, aggregating all of the separate session data items into one type.

But the definition of the Singleton pattern is very explicit, and misapplying the term and confusing its intent is undesirable.

You should also consider the negative consequences of this approach in more detail. For example, you have completely overlooked the impact of adding a new piece of session data in terms of increased testing.

You also need to consider the inherent weakness in the implementation in that it doesn't recognise loss of session (due to timeout, for example). It thus does not come close to representing a proper singleton.

The article would thus be improved by (a) making it clear that this is NOT a singleton, (b) by covering negative consequences of the implementation correctly and (c) by examining alternative strategies for dealing with the loss of a session.
Title: i got the error   
Name: manivannan53@rediffmail.com
Date: 2007-04-17 6:36:58 AM
Comment:
in .Net 2003 we create a session item using session.item("variable").how can we create in .Net 2005
Title: end user can also understand   
Name: fani
Date: 2006-04-25 8:28:10 AM
Comment:
excellent ,fine and fantastic
Title: Re: Jimmy   
Name: Robert Boedigheimer
Date: 2005-10-26 8:03:55 PM
Comment:
The singleton pattern is useful when you want a single instance of an object to be created. WITHIN the context of an individual user's session their will be a single instance created with the above solution. It saves pages from always checking if it is null first then create one if it does not already exist (and avoids mistakes where someone just creates an additional instance).

I won't repeat the advantages/disadvantages here again since they are in the article. Our experience looking at our ASP sites when we moved to ASP.Net was that we tons of individual session variables all over with no grouping so people could misinterpret what context they were meant to be used in. People also duplicated stuff because they did not know out of a list of a couple hundred session variables which one might be what they already needed.

A practical example is that we use one of these to store the active customer for a session. After they log on we hit our internal database and cache additional info about the customer (address, etc) in session.

We can dialog more directly about it if you want to email me at robertb@aspalliance.com.

P.S. Glad you liked the server side viewstate article
Title: My   
Name: Jimmy
Date: 2005-10-26 2:27:16 AM
Comment:
Your article on putting View State on the server. Great, actually a solution I have recommended to people in the past also, along with reducing what they keep viewstate enabled on. But this article wont cut mustard for me. Sorry, and sorry for the double post.
Title: Mr   
Name: Jimmy
Date: 2005-10-26 2:07:13 AM
Comment:
Honestly I must be missing the point. Please feel free to show me the light.

The Singleton pattern says that there is always exactly ONE instance of "Smart_Session", instead you are hiding the constructor to control when new instances are created. And since there's multiple instances (per Session), again another technicality that indicates this is not a singleton.

Without mincing what is an is not a singleton.
- ASP.Net is not a completely unstructured language.
- It's not a hard task to test if there is an object in a session variable. Then either create one or use it after that.
- I still fail to see why you would create an object to do what the session object already does in the first place. Not only this you are storing the object in the session object again. Is it being more memory efficient, I can't see how yet.
Title: Re: Jimmy   
Name: Robert Boedigheimer
Date: 2005-10-21 7:43:36 AM
Comment:
There are many instances in web sites where it is necessary to ensure that a single object is created for a particular user (user object, etc). It is a singleton within the context of an individual user which is extremely useful.
Title: Mr   
Name: Jimmy
Date: 2005-10-21 3:04:56 AM
Comment:
A singleton that gets instantiated for every session... Doesn't ring out singleton anymore.
Title: Singleton Sessions are unreliable   
Name: Cambpell
Date: 2005-10-21 2:59:04 AM
Comment:
How come the comments on code project are all negative?

It is the same implementation:
http://www.codeproject.com/Purgatory/aspnet_singleton_session.asp?df=100&forumid=55574&select=1259715&msg=1259715#xx837983xx
Title: Consultant   
Name: Anik Majumder
Date: 2005-06-03 4:13:05 PM
Comment:
After going through so many web site, I think...this one is very usefull.
Thanks alot
Title: MR.   
Name: ShavG
Date: 2005-04-15 11:48:56 PM
Comment:
Really grate. I found very useful
Title: excellent   
Name: DEMiR
Date: 2005-01-26 1:06:29 AM
Comment:
Creative, simple and very useful. Thanks very much Robert
Title: Good Stuff!   
Name: Vik
Date: 2005-01-07 4:39:17 PM
Comment:
Helpful and very informative!!
Title: Consultant   
Name: Tonchi Korsano
Date: 2004-12-15 4:29:27 PM
Comment:
Really nice explanation how singleton sessions work.
I have used only singleton for .net remoting from web.config files (caller and receiver). I also used only cao to solve a database table call. However, most of the time, I have configures this web.configs to singlecall.
Great!!

Tonchi.
Title: Explained superbly   
Name: Suresh
Date: 2004-09-30 8:24:22 AM
Comment:
This article was really good and useful to me. One of my project implemented this and worked out fine.
Thanks Robert






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-10-06 9:49:47 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search