通过 IoC 将依赖项提供给工厂类?
我有一个工厂类,它决定应该实例化并返回四个可用子类中的哪一个。正如您所期望的,所有子类都实现相同的接口:
public static class FooFactory{
public IFoo CreateFoo(FooEnum enum){
switch (enum)
{
case Foo1:
return new Foo1();
case Foo2:
return new Foo2();
case Foo3:
return new Foo3(IBar);//has a constructor dependency on IBar
case Foo4:
return new Foo4();
default:
throw new Exception("invalid foo!");
}
}
}
如您所见,其中一个子类在其构造函数中定义了依赖项。
一些兴趣点:
- 我们使用 Spring.NET 作为我们的 IoC。
IFoo
的所有子类都是域对象,因此不会被 Spring.NET 实例化。如果可能的话,我希望保持这种状态。- 该应用程序有一个手写的数据访问层 (puke),因此这里没有 ORM 发挥作用。
我试图找出如何最好地将 IBar
依赖项从 FooFactory
传递到 Foo3
中。我感觉这可能是通过 IoC 最好解决的问题,但我不太明白如何解决。我还希望使 FooFactory 尽可能保持可单元测试:即我不希望在我的测试代码中依赖 Spring.NET。
感谢您的阅读。
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:
public static class FooFactory{
public IFoo CreateFoo(FooEnum enum){
switch (enum)
{
case Foo1:
return new Foo1();
case Foo2:
return new Foo2();
case Foo3:
return new Foo3(IBar);//has a constructor dependency on IBar
case Foo4:
return new Foo4();
default:
throw new Exception("invalid foo!");
}
}
}
As you can see, one of the subclasses has a dependency defined in its constructor.
Some points of interest:
- We're using Spring.NET as our IoC.
- All subclasses of
IFoo
are domain objects and therefore are not being instantiated by Spring.NET. I'd like to keep things this way if at all possible. - The application has a hand written Data Access Layer (puke) so no ORM is in play here.
I'm trying to figure out how best to pass the IBar
dependency into Foo3
from FooFactory
. I get the feeling that this might be a problem best resolved via IoC but I can't quite grok how. I also want to keep FooFactory
as unit testable as possible: i.e. I'd prefer not have to have dependencies on Spring.NET in my test code.
Thanks for reading.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将 FooFactory 更改为抽象工厂,并将 IBar 实例注入到具体实现中,如下所示:
请注意,FooFactory 现在是一个实现 IFooFactory 接口的具体非静态类:
在代码中任何需要的地方一个 IFoo 实例,然后您将依赖于 IFooFactory 并使用其 CreateFoo 方法来创建您需要的实例。
您可以使用任何有价值的 DI 容器来连接 FooFactory 及其依赖项。
Change FooFactory to an Abstract Factory and inject the IBar instance into the concrete implementation, like this:
Notice that FooFactory is now a concrete, non-static class implementing the IFooFactory interface:
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.
听起来你既想要蛋糕又想吃它。你需要致力于国际奥委会的战略。
你会产生一个斗鱼代码,小鸡们也会更喜欢你....;p
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