Service locator for generics

前端 未结 1 1606
日久生厌
日久生厌 2021-01-24 02:04

I have say a dozen types T which inherit from EntityObject and IDataObject. I have generic the following interface

IDataMa         


        
相关标签:
1条回答
  • 2021-01-24 02:44

    Here is a neat solution if having the locator as singleton is fine:

    static class Locator
    {
        private static class LocatorEntry<T> where T : ...
        {
            public static IDataManager<T> instance;
        }
    
        public static void Register<T>(IDataManager<T> instance) where T : ...
        {
            LocatorEntry<T>.instance = instance;
        }
    
        public static IDataManager<T> GetInstance<T>() where T : ...
        {
            return LocatorEntry<T>.instance;
        }
    }
    

    If you cannot implement the locator as singleton, I believe there is no there around creating a Dictionary<Type,object> and do some casts:

    class Locator
    {
        private readonly Dictionary<Type, object> instances;
    
        public Locator
        {
            this.instances = new Dictionary<Type, object>();
        }
    
        public void Register<T>(IDataManager<T> instance) where T : ...
        {
            this.instances[typeof(T)] = instance;
        }
    
        public IDataManager<T> GetInstance<T>() where T : ...
        {
            return (IDataManager<T>)this.instances[typeof(T)];
        }
    }
    
    0 讨论(0)
提交回复
热议问题