Factory method with DI and IoC

后端 未结 6 664
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 15:30

I am familiar with these patterns but still don\'t know how to handle following situation:

public class CarFactory
{
     public CarFactory(Dep1,Dep2,Dep3,De         


        
6条回答
  •  深忆病人
    2020-11-22 15:49

    Many DI containers support the notion of named dependencies.

    E.g. (Structuremap syntax)

    For().Use().Named("aCar");
    Container.GetNamedInstance("aCar") // gives you a CarA instance
    

    If you use something like a convention, a rule how the name is derived from the concrete car type itself, you have a situation where you don't need to touch the factory anymore when you extend the system.

    Using this in a factory is straightforward.

    class Factory(IContainer c) {
      public ICar GetCar(string name) {
        Return c.GetNamedInstance(name);
      }
    }
    

提交回复
热议问题