Monday, February 18, 2008

Singleton Class WinForm\WebForm

If you use static object in ASP.NET application, this works as Application object and is shared across all sessions. To create a user visible properties, we use session objects. A better way of using this is to use Singelton class. This class creates only one object and same object is refeneced again without new creation. The following code could be used to create a common Singleton class for windows and web application.

using System;
using System.Data;
using System.Configuration;
using System.Web;

namespace Common
{
///


/// Summary description for SessionConfig
///

public class StateData
{

#region PROPERTIES
string currentUser;
public string CurrentUser
{
get { return this.currentUser; }
set { this.currentUser = value; }
}
#endregion

private static StateData oInstance;

protected StateData()
{
}


public static StateData Instance
{
get
{
// If called from windows, this would be null. Use Static object then
if (System.Web.HttpContext.Current == null)
{
if (oInstance == null)
{
oInstance = new StateData();
}
return oInstance;
}
if (HttpContext.Current.Session == null || HttpContext.Current.Session["SharedData"] == null)
HttpContext.Current.Session.Add("SharedData", new StateData());


return (StateData)System.Web.HttpContext.Current.Session["SharedData"];
}
}

}
}

0 comments: