G
Guest
Hi all - I've taken some code from MSDN and made a Generic singleton, so that
I don't have to write this code in many places:
public class Singleton<TEntity> where TEntity : class, new()
{
private static volatile TEntity instance = default(TEntity);
private static object syncRoot = new Object();
public static TEntity Instance
{
get
{
if (instance == default(TEntity))
{
lock (syncRoot)
{
if (instance == default(TEntity))
{
//instance = new TEntity();
}
}
}
return instance;
}
}
}
You would use it like this:
public class MyClass : Singleton<MyClass>
....
This works great - except that MyClass must have a public parameterless
constructor. Is there any way of getting around this? I have yet to find an
implementation that allows me to do what I want.
Thanks,Phil
I don't have to write this code in many places:
public class Singleton<TEntity> where TEntity : class, new()
{
private static volatile TEntity instance = default(TEntity);
private static object syncRoot = new Object();
public static TEntity Instance
{
get
{
if (instance == default(TEntity))
{
lock (syncRoot)
{
if (instance == default(TEntity))
{
//instance = new TEntity();
}
}
}
return instance;
}
}
}
You would use it like this:
public class MyClass : Singleton<MyClass>
....
This works great - except that MyClass must have a public parameterless
constructor. Is there any way of getting around this? I have yet to find an
implementation that allows me to do what I want.
Thanks,Phil