I currently have a collection of 6 or 7 singletons, all of which do almost the same thing (see the For
method in the below example) but with a different internal DB query and return a collection of different objects (so parsing the DB results is different in each singleton).
Therefore, using this question as my base, I've been trying to build an abstract generic base class in C# for these singletons.
There are similar questions on SO but none implement Lazy
, which I wish to.
So far I have this
public abstract class SingletonBase<T> where T : class, new()
{
private static Lazy<SingletonBase<T>> _lazy;
private static readonly object _lock = new object();
public static SingletonBase<T> Instance
{
get
{
if (_lazy != null && _lazy.IsValueCreated)
{
return _lazy.Value;
}
lock (_lock)
{
if (_lazy != null && _lazy.IsValueCreated)
{
return _lazy.Value;
}
***** this is the problem line *****
_lazy = new Lazy<SingletonBase<T>>(new T());
}
return _lazy.Value;
}
}
public abstract IEnumerable<T> For(string systemLangCode);
}
However, a problem occurs on the line
_lazy = new Lazy<SingletonBase<T>>(new T());
Visual Studio tells me "Cannot resolve constructor 'Lazy<T>'."
I'm unsure what should be passed into the constructor for Lazy<SingletonBase<T>>
, or have I gone in the wrong direction?