Service locator for generics

前端 未结 1 1607
日久生厌
日久生厌 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条回答
  •  梦毁少年i
    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 where T : ...
        {
            public static IDataManager instance;
        }
    
        public static void Register(IDataManager instance) where T : ...
        {
            LocatorEntry.instance = instance;
        }
    
        public static IDataManager GetInstance() where T : ...
        {
            return LocatorEntry.instance;
        }
    }
    

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

    class Locator
    {
        private readonly Dictionary instances;
    
        public Locator
        {
            this.instances = new Dictionary();
        }
    
        public void Register(IDataManager instance) where T : ...
        {
            this.instances[typeof(T)] = instance;
        }
    
        public IDataManager GetInstance() where T : ...
        {
            return (IDataManager)this.instances[typeof(T)];
        }
    }
    

    0 讨论(0)
提交回复
热议问题