Dependency Injection and the Strategy Pattern

前端 未结 5 1496
灰色年华
灰色年华 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:12

    This is a late response but maybe it will help others.

    I have a pretty simple approach. I simply create a StrategyResolver to not be directly depending on Unity.

    public class StrategyResolver : IStrategyResolver
    {
        private IUnityContainer container;
    
        public StrategyResolver(IUnityContainer unityContainer)
        {
            this.container = unityContainer;
        }
    
        public T Resolve(string namedStrategy)
        {
            return this.container.Resolve(namedStrategy);
        }
    }
    

    Usage:

    public class SomeClass: ISomeInterface
    {
        private IStrategyResolver strategyResolver;
    
        public SomeClass(IStrategyResolver stratResolver)
        {
            this.strategyResolver = stratResolver;
        }
    
        public void Process(SomeDto dto)
        {
            IActionHandler actionHanlder = this.strategyResolver.Resolve(dto.SomeProperty);
            actionHanlder.Handle(dto);
        }
    }
    

    Registration:

    container.RegisterType("One");
    container.RegisterType("Two");
    container.RegisterType();
    container.RegisterType();
    

    Now, the nice thing about this is that I will never have to touch the StrategyResolver ever again when adding new strategies in the future.

    It's very simple. Very clean and I kept the dependency on Unity to a strict minimum. The only time I would have touch the StrategyResolver is if I decide to change container technology which is very unlikely to happen.

    Hope this helps!

提交回复
热议问题