feeding dependencies to a factory class via IoC?

时光怂恿深爱的人放手 提交于 2019-11-30 15:41:58

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!