Sunday, April 19, 2009

Generic Singleton method

This is a general purpose method to create a singleton. It uses generics and takes two arguments, one is the type of the singleton and the other is the type of the interface you wish to return (this is optional). Notice that the method is thread safe, there is a double check to verify that another thread did not create instance after the first if statement. The idea is to have the lock done only once if possible.

Code looks like this:


private static TInterface GetSingleton(ref TInterface instance)
where TComponent : class, TInterface, new()
{
try
{
if (instance == null)
{
lock (mLockObject)
{
if (instance == null)
{
instance = new TComponent();
}
}
}
return instance;
}
catch (Exception ex)
{
LogException(ex);
throw ex;
}
}

1 comment:

alex o. said...

Thread-safety of the double-check lock pattern is debatable and in general not portable (it works in .NET 2.0 implementation of CLI, but may fail under CLI implemented according to ECMA specification).
See this very good post on singletons and thread safety:
http://www.yoda.arachsys.com/csharp/singleton.html