Quantcast
Channel: .NET Framework Class Libraries forum
Viewing all articles
Browse latest Browse all 8156

Generic singleton instance generator

$
0
0

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;
        }
    }


Viewing all articles
Browse latest Browse all 8156

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>