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;
}
}