Click here to Skip to main content
Click here to Skip to main content

using the singleton design pattern for managing session state in asp.net

By , 30 May 2004
 

Introduction

Hello, A few days back I was trying to design and develop a session object(a stand alone class) dealing with asp.net session varibales.The problem I faced was if I create a stand alone class in a project and assigned property’s to it(variables which I wanted to persist) ,and instantiate that class from the global.asax session start event ,this looked pretty fine in the beginning as I was only using these variables in the code behinds, but when I tried accessing these variables from other classes in the application, I couldn’t do it ,because the object was not in the same context (System.Web.HttpContext).So I did some research here and there and decided to use the singleton design patternto solve this problem. If you are new to this pattern you should read this article on msdn .

(http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/singletondespatt.asp)

So I created a stand alone class Smart_Session and assigned property methods to it. And a static method which gets the object out of the session and returns it to the caller (both aspx and .cs files).And this class always returns a single instance at any call.

The code below is an example of one such class and can be referred to in code as per the following code:

<P>public class someclass</P>
<P>{
Smart_Session oSession = Smart_Session.GetCurrentSmart_Session();


<P>public string someMethod()
</P>

<P> <P>{
<P> 
<P>oSession.Get_Set_Get_Set_prod_id =007;


<P>}</P>


<P>}
</P>

Example of Smart_Session


 <PRE>public class Smart_Session 
{
private const string SMART_SESSION = "SESGLOBAL";
private bool init;
private string user_name;
private string user_pwd;
private int lang_id;
private int acc_id;
private string purch_id;
private int purch_date;
private int serial_no;
private string prod_id;
private string pkg_id; 
private string err_msg;
private string email_id;
private Smart_Session()
{
Refresh();
}
public void Refresh()
{
this.prod_id = "";
this.serial_no = 0;
this.purch_date = 0;
this.purch_id = "";
this.acc_id = 0;
this.lang_id = 0;
this.pkg_id = null;
this.init = false;
this.err_msg = "";
this.email_id=""; 
}
public string GetSetEmailID
{
get
{
return this.email_id;
}
set
{
this.email_id = value;
}
}
public string GetSetPassword
{
get
{
return this.user_pwd;
}
set
{
this.user_pwd = value;
}
}
public string GetSetUserName
{
get
{
return this.user_name;
}
set
{
this.user_name = value;
}
}
public string Get_Set_prod_id
{
get
{
return this.prod_id;
}
set
{
this.prod_id = value;
}
}
public int Get_Set_serial_no
{
get
{
return this.serial_no;
}
set
{
this.serial_no = value;
}
}
public int Get_Set_purch_date
{
get
{
return this.purch_date;
}
set
{
this.purch_date = value;
}
}
public string Get_Set_purch_id
{
get
{
return this.purch_id;
}
set
{
this.purch_id = value;
}
}
public int Get_Set_acc_id
{
get
{
return this.acc_id;
}
set
{
this.acc_id = value;
}
}
public int Get_Set_lang_id
{
get
{
return this.lang_id;
}
set
{
this.lang_id = value;
}
}
public string Get_Set_pkg_id
{
get 
{
return this.pkg_id;
}
set
{
this.pkg_id=value;
}
}
public string Get_Set_spErrorMsg
{
get 
{
return this.err_msg;
}
set
{
this.err_msg=value;
}
}
public bool init_Status
{
get
{
return this.init;
}
}
public static Smart_Session GetCurrentSmart_Session()
{
Smart_Session oSmart_Session;
{
if (null == System.Web.HttpContext.Current.Session[SMART_SESSION])
{
//No current session object exists, use private constructor to 
// create an instance, place it into the session
oSmart_Session = new Smart_Session();
System.Web.HttpContext.Current.Session[SMART_SESSION] = oSmart_Session;
}
else
{
//Retrieve the already instance that was already created
oSmart_Session = (Smart_Session)System.Web.HttpContext.Current.Session[SMART_SESSION];
}
//Return the single instance of this class that was stored in the session
return oSmart_Session;
}
}
}

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).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

purushdeo
Web Developer
United States United States
Hi I am Purush ,I'm a Consultant on the .NET Framework , Software engineering. My Recent work includes various ASP. Net web portals on windows 2000/CE.net platforms.
 
Over 6 years experience in design, development, and implementation of applications in Internet, Intranet, client/server, and desktop environments. Diverse background working both as permanent employee and contract consultant for several major Fortune 500 corporations and small start-ups in a wide range of industries. Seeking opportunities utilizing experience and skills in application design, development, specifications, usability, e-commerce, Internet marketing, process automation, and problem solving.Specializing in: .Net Programming, ASP.Net, VB.Net, C#, ADO. Net, XML, SQL Server 2000, Visual Studio, Web Design, Web Development.

 

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberPaulo Zemek11-Nov-09 0:33 
It's impossible to understand the sample, as there are PRE tags for each line (instead of the full source).   The reason for use it, as stated, is that "the code is not in the same context", but the variable is read from the HttpContext and, so, if that's the problem, the problem will...
Questionif your solutions fix my problem?memberdsmportal7-Aug-07 17:51 
what is the best pattern to get/set session variable across application? i have scenario where when my session variable can change through the application how should i take care?   currently, i'm doing something like the below code... but there a hickup the way i'm doing... here is what...
JokeVery HelpfulmemberSenthil v v1-Feb-06 6:00 
I was trying to add a base page and derive all the page from the webpage I was not able to access System.Web.HttpContext.Current.Session[], becuase its not available when the objects are created.Its only available after the page_load(). I then refered your article and then used this to move on...
Questionthread safe?sussAnonymous12-Jul-05 22:54 
Can anyone tell me how threadsafe this is? I need a singleton for each session.
AnswerRe: thread safe?membervadivhere21-Sep-05 4:11 
Actually, this is not right and this articles shows how a singleton can be wrongly designed.   When you want to dealwith something whihc should be accessable for your whole application then it should be a Application object or else a Cache object.  
GeneralRe: thread safe?memberpostmaster@appointmentsbook.com20-Oct-05 20:34 
Using singletons as described in this article will get you in trouble!   Stick with vadivhere's comments and you will see more predictable results.  
GeneralObject reference not set to an instance of an objectmemberforest_tmm20-Jan-05 14:57 
When I try to test your code in a new web application. I always get the following errors:
 
System.NullReferenceException: Object reference not set to an instance of an object.
 
at line:
 
if (null==System.Web.HttpContext.Current.Session[SMART_SESSION])
 

What's the problem? Have you ever make it work?
GeneralRe: Object reference not set to an instance of an objectmembersholliday28-Nov-05 8:00 
Create a default.aspx page... and do NOT put the call to the Singleton in it.   Then create a WebForm1.aspx page, and do put the call to the singleton code in there.   Set the startup page to "default.aspx", and put a linkbutton on there ,, which redirects you to the...
GeneralNot singletonmemberEric Newton6-Nov-04 9:53 
This is not singleton design.   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...
GeneralQuestion...memberHumanOsc31-May-04 20:31 
I have a little question about your singleton design pattern... Why you don't use it as a Application Variable ??? You have also only one Global object in your Project...   Please explain your decision... It's possible that your design have some advantages in point of the Global...
GeneralRe: Question...memberGasparDax19-Nov-06 17:57 
Hi, the difference between storing variable in the Application from Session is that, if you store your object in the Application it would be availble to all users who enters your site, irregardless of Session.If it is stored in the session the data would only be avaible to the user of that...

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130619.1 | Last Updated 31 May 2004
Article Copyright 2004 by purushdeo
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid