Object Oriented Programming Patterns for Geeks
A Web Application Singleton
You could consider this singleton to be the web application friendly version of the SimpleSingleton. It lives inside the HttpContext Application dictionary as a serialized object, but other than that there is very little operational difference - aside from of course the fact that you have to ensure that any classes used inside it are also serializable if you require them to be persistant.
In more complicated incarnations this form of class can allow all sorts of extensions to your web applications model. Using the various facilities available in .NET for instance you can engineer real-time configuration updates, give the web application the ability to communicate as a single entity across application domains and all sorts of other useful tricks.
Okay, so perhaps you could also achieve this using the SimpleSingleton, except that in this format you can also take advantage of the Application functionality of the website.
[Serializable]
public sealed class ApplicationSingleton
{
private const string APP_KEY
= "MyApp_593706A0-DDDA-4d37-8173-7718B2C6EB76";
/// <summary>
/// Some basic instance data.
/// </summary>
private string _SomeInstanceData;
/// <summary>
/// Gets or sets some instance data.
/// </summary>
/// <value>Some instance data.</value>
public string SomeInstanceData
{
get { return this._SomeInstanceData; }
set { this._SomeInstanceData = value; }
}
/// <summary>
/// Initializes a new instance of the
/// <see cref="ApplicationSingleton"/> class.
/// This is privately invoked
/// </summary>
private ApplicationSingleton()
{
this._SomeInstanceData = "Hi!";
}
/// <summary>
/// Gets the singleton.
/// </summary>
/// <value>The singleton.</value>
public static ApplicationSingleton Session
{
get
{
// double check locking...
if (HttpContext.Current.Application[APP_KEY] == null)
try
{
HttpContext.Current.Application.Lock();
if (HttpContext.Current.Application[APP_KEY] == null)
HttpContext.Current.Application[APP_KEY] =
new ApplicationSingleton();
}
finally
{
HttpContext.Current.Application.UnLock();
}
return HttpContext.Current.Session[APP_KEY]
as ApplicationSingleton;
}
}
}