Dependency Injection and the Strategy Pattern

前端 未结 5 1493
灰色年华
灰色年华 2020-12-02 23:59

There is an enormous amount of discussion on this topic, but everyone seems to miss an obvious answer. I\'d like help vetting this \"obvious\" IOC container solution. Th

5条回答
  •  旧巷少年郎
    2020-12-03 00:16

    I'd implement something like this.

    public interface IAbstractFactory
    {
        IFiledAppSettingsFactory this[Provider provider] { get; }
    }
    
    public Enum : int 
    { 
       One =1, Two =2, Three =3
    }
    
    
    internal class AbstractFactory : IAbstractFactory
    {
        public AbstractFactory(/** dependencies **/)
        {
        }
    
        private readonly IReadOnlyDictionary services
           = new Dictionary
        {
           { Provider.One , new Factory1(/** dependencies comming from AbstractFactory **/) },
           { Provider.Two , new Factory2(/** no dependencies **/) },
           { Provider.Three, new Factory3(/** maybe more dependencies comming from AbstractFactory **/) },
        };
    
        IFactory IAbstractFactory.this[Provider provider] => this.services[provider];
    }
    
    internal sealed class Factory1: IFactory
    {
        internal FiledSelfFactory(/** any dependencies will come from AbstractFactory **/)
        {
        }
    }
    
    internal sealed class Factory2: IFactory
    {
        internal FiledSelfFactory(/** any dependencies will come from AbstractFactory **/)
        {
        }
    }
    
    internal sealed class Factory3: IFactory
    {
        internal FiledSelfFactory(/** any dependencies will come from AbstractFactory **/)
        {
        }
    }
    
    public static void AddAppSettings(this IServiceCollection serviceDescriptors)
    {
        serviceDescriptors.AddSingleton();
    }
    
    
    public class Consumer
    {
        private readonly IFactory realFactory;
        public Consumer(IIAbstractFactory factory) 
        {
              realFactory = factory[Provider.One]
        }
    }
    

提交回复
热议问题