Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET
Article

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

Rate me:
Please Sign up or sign in to vote.
1.03/5 (13 votes)
30 May 20042 min read 62.3K   388   17   12
.NET guy

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:

C#
<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
C#
{
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


Written By
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.



Comments and Discussions

 
Suggestiontutorial Pin
Member 1199173318-Sep-15 6:11
Member 1199173318-Sep-15 6:11 
GeneralMy vote of 1 Pin
Paulo Zemek11-Nov-09 0:33
mvaPaulo Zemek11-Nov-09 0:33 
Questionif your solutions fix my problem? Pin
dsmportal7-Aug-07 17:51
dsmportal7-Aug-07 17:51 
JokeVery Helpful Pin
Senthil v v1-Feb-06 6:00
Senthil v v1-Feb-06 6:00 
Questionthread safe? Pin
Anonymous12-Jul-05 22:54
Anonymous12-Jul-05 22:54 
AnswerRe: thread safe? Pin
vadivelkumar21-Sep-05 4:11
vadivelkumar21-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.

Poke tongue | ;-P
GeneralRe: thread safe? Pin
AbuseByUnkindPeople20-Oct-05 20:34
AbuseByUnkindPeople20-Oct-05 20:34 
GeneralObject reference not set to an instance of an object Pin
forest_tmm20-Jan-05 14:57
forest_tmm20-Jan-05 14:57 
GeneralRe: Object reference not set to an instance of an object Pin
granadaCoder28-Nov-05 8:00
granadaCoder28-Nov-05 8:00 
GeneralNot singleton Pin
Eric Newton6-Nov-04 9:53
Eric Newton6-Nov-04 9:53 
GeneralQuestion... Pin
HumanOsc31-May-04 20:31
HumanOsc31-May-04 20:31 
GeneralRe: Question... Pin
GasparDax19-Nov-06 17:57
GasparDax19-Nov-06 17:57 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.