Here is a quick one... There is often a lot of debate about the use of Singleton's in Web environments, but they can make a lot of sense. With that said, using a Per-Request Singleton in a Web Application without considering thread-safety will lead to results that are... well... dubious. A typical Singleton pattern such as the one below is thread-safe under normal circumstances but when it comes to ASP.NET Applications the threading behaviours; per request; are unique. The consequence of this "uniqueness" leads to the below pattern no longer being safe at least insofar as having a single instance per request:
public sealed class TypicalSingleton
{
static TypicalSingleton _instance;
static readonly object _padlock = new object();
public static TypicalSingleton Current
{
get
{
lock (_padlock)
{
if (_instance == null)
_instance = new TypicalSingleton();
return _instance;
}
}
}
}
If you wish to have an instance per web request, you can do so with the following pattern, and this can easily be created, read, and/or modified within the HTTP pipeline using HTTP Modules as well as use within the application itself:
public sealed class WebContextSingleton
{
private const string ContextKey = "WebContextSingleton";
public static WebContextSingleton Current
{
get
{
var instance = HttpContext.Current.Items[ContextKey] as WebContextSingleton;
if (instance == null)
{
instance = new WebContextSingleton();
HttpContext.Current.Items.Add(ContextKey, instance);
}
return instance;
}
}
}
See... I told you... a quick one.
Tags: threading, design patterns