feeding dependencies to a factory class via IoC?

前端 未结 2 856
执笔经年
执笔经年 2021-01-03 02:32

I have a factory class that decides which of four available subclasses it should instantiate and return. As you would expect, all subclasses implement the same interface:

相关标签:
2条回答
  • 2021-01-03 03:26

    Change FooFactory to an Abstract Factory and inject the IBar instance into the concrete implementation, like this:

    public class FooFactory : IFooFactory {
         private readonly IBar bar;
    
         public FooFactory(IBar bar)
         {
             if (bar == null)
             {
                 throw new ArgumentNullException("bar");
             }
    
             this.bar = bar;
         }
    
         public IFoo CreateFoo(FooEnum enum){
                switch (enum)
                {
                    case Foo1:
                        return new Foo1();
                    case Foo2:
                        return new Foo2();
                     case Foo3:
                        return new Foo3(this.bar);
                    case Foo4:
                        return new Foo4();
                     default:
                        throw new Exception("invalid foo!");
                }
         }
    }
    

    Notice that FooFactory is now a concrete, non-static class implementing the IFooFactory interface:

    public interface IFooFactory
    {
        IFoo CreateFoo(FooEnum emum);
    }
    

    Everywhere in your code where you need an IFoo instance, you will then take a dependency on IFooFactory and use its CreateFoo method to create the instance you need.

    You can wire up FooFactory and its dependencies using any DI Container worth its salt.

    0 讨论(0)
  • 2021-01-03 03:26

    sounds like you want your cake and to eat it too. you need to commit to your IOC strategy.

    you will produce mo an betta code and the chicks will dig you more too.... ;p

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