Hi,
I am looking for a class which can return singleton instance of the type that client specifies. I want to use "Lazy" keyword feature so that I don't need to make the method thread-safe.
Current working solution I have is below but I need to take care of thread safe here :(
public class InstanceGenerator { static Dictionary<string, object> typeDict = new Dictionary<string, object>(); static readonly object lockObj = new object(); public static object GetInstance(string type) { lock (lockObj) { if (!typeDict.ContainsKey(type)) typeDict.Add(type, Activator.CreateInstance(Type.GetType(type))); } return typeDict[type]; } } // Client var obj = InstanceGenerator.GetInstance("GenericSingleton.Sample");
While I am looking for something like below but I want to pass type value as string from client-
public abstract class SingletonBase<T> where T : class { private static readonly Lazy<T> sInstance = new Lazy<T>( () => CreateInstanceOfT()); public static T Instance(string typeName) { return sInstance.Value; } private static T CreateInstanceOfT() { return Activator.CreateInstance(typeof(T), true) as T; } }