Implementing a singleton pattern on a given session

  • Thread starter Thread starter RSH
  • Start date Start date
R

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.

Thanks!
RSH
 
Hello RSH,

Why not to use the session then? which works like singleton in your case?

---
WBR,
Michael Nemtsev [.NET/C# MVP] :: blog: http://spaces.live.com/laflour

"The greatest danger for most of us is not that our aim is too high and we
miss it, but that it is too low and we reach it" (c) Michelangelo


R> Is it possible to implement a singleton on a given session under asp
R> .net? While purists would say than thats technically not a singleton,
R> i dont know what else to call it.
R>
R> Thanks!
R> RSH
 
Hello RSH,

why not to use just the sesion in this case?

---
WBR,
Michael Nemtsev [.NET/C# MVP] :: blog: http://spaces.live.com/laflour

"The greatest danger for most of us is not that our aim is too high and we
miss it, but that it is too low and we reach it" (c) Michelangelo


R> Is it possible to implement a singleton on a given session under asp
R> .net? While purists would say than thats technically not a singleton,
R> i dont know what else to call it.
R>
R> Thanks!
R> RSH
 
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.
 
Back
Top