I have a Singleton in my Project looking like this:
//Create a Singleton
static MySingleton Instance;
private static readonly object Padlock = new object();
/// <summary>
/// Singelton Method, to make sure only one instance of this class exists at runtime.
/// </summary>
/// <returns></returns>
public static MySingleton GetInstance()
{
//Thread Safety
lock (Padlock)
{
if (Instance == null)
{
Instance = new MySingleton();
}
return Instance;
}
}
private MySingleton()
{
}
//[...]
The Singleton contains several other classes as Properties, which should never be null.
Normally I'd use DependencyInjection to gurantee each new object gets all necessary parameters on instantiation. Like this:
IHelperClass Helper {get; set;}
IExectiveClass Executive {get; set;}
public NotMySingleton(IHelperclass helper, IExecutiveClass executive)
{
Helper = helper;
Executive = executive;
}
But I have no idea how to combine DependencyInjection with a Singleton Pattern.
Is there a way to use Singletons with DependenyInjection? What is common practice? What alternatives do I have (if this is not a suitable option)?
MySingleton
into the constructor of any consumer that depends on it. – Eddyede