Hello RSH,
Is it possible to implement a singleton on a given session under asp
.net? While purists would say than thats technically not a singleton,
i dont know what else to call it.
It's quite easy. Just make sure the static Instance property or method will
save and fetch the object from the session instead of from a static member.
public class SessionSingleton
{
public static SessionSingleton Instance
{
private SessionSingleton(){}
get
{
// You need to add locking if you want to use this variable
multithreaded. The easy thing is that if you're not using threads yourself,
ASP.NET will make sure the session scope is exclusive to the current page.
SessionSingleton result = Session["MYCONSTANT"];
if (result == null)
{
result = new SessionSingleton();
Session["MYCONSTANT"] = result;
}
return result;
}
public string SomeMethod()
{
return "From the SessionSingleton";
}
}
}
We use this method quite often to 'shield' the actual Session object from
the programmer and force him to use a typed method to access his values.