I have a question, is this the correct approach to make a Generic Singleton?
public class Singleton<T> where T : class, new()
{
private static T instance = null;
private Singleton() { }
public static T Instancia
{
get
{
if (instance == null)
instance = new T();
return instance;
}
}
}
EDIT:
Checking some PDFs I found a generic Singleton made this other way, is this other correct?
public class Singleton<T> where T : class, new()
{
Singleton() { }
class SingletonCreator
{
static SingletonCreator() { }
// Private object instantiated with private constructor
internal static readonly T instance = new T();
}
public static T UniqueInstance
{
get { return SingletonCreator.instance; }
}
}
It is possible without reflection.
We just need a generic class for the singleton pattern which takes two parameter - the implementation of the concrete singleton class and the interface for the concrete singleton. The generic singleton class implements the singleton pattern and all the stuff you need - for example logging, locks or what else.
For a generic piece of code that will be reused, you should consider thread safety at the point where you create the singleton instance.
As it is,
(instance == null)
could evaluate to true on separate threads.