问题描述
我有一个工厂类,决定应该实例化和返回四个可用的子类中的哪一个。正如你所期望的,所有的子类实现相同的接口:
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.
有些兴趣点:
- 我们使用Spring.NET我们的IoC。
-
IFoo
的所有子类都是域对象,因此不会被Spring.NET实例化。 - 应用程序有一个手写的数据访问层(puke),所以没有ORM在这里播放。
- 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.
我想知道如何最好地将 IBar
依赖项传递到 Foo3
从 FooFactory
。我得到的感觉,这可能是一个问题最好通过IoC解决,但我不能grok如何。我也想保持 FooFactory
尽可能单元测试:ie我不想在我的测试代码中依赖于Spring.NET。
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.
感谢阅读。
推荐答案
将FooFactory更改为 >并注入IBar实例到具体的实现,像这样:
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!");
}
}
}
注意FooFactory现在是具体的非静态类实现IFooFactory接口:
Notice that FooFactory is now a concrete, non-static class implementing the IFooFactory interface:
public interface IFooFactory
{
IFoo CreateFoo(FooEnum emum);
}
在您需要IFoo实例的代码中,依赖于IFooFactory并使用它的CreateFoo方法来创建你需要的实例。
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.
你可以使用任何一个值得使用的DI容器来连接FooFactory及其依赖。
You can wire up FooFactory and its dependencies using any DI Container worth its salt.
这篇关于通过IoC向工厂类提供依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!