构造函数注入-我们是否也注入工厂? [英] Constructor Injection - Do we inject factories as well?
问题描述
听了清洁代码讨论之后,我了解到我们应该使用工厂来组成对象。因此,例如,如果房屋
具有门
和门
有一个 DoorKnob
,在 HouseFactory
中,我们创建了一个新的 DoorKnob
并将其传递给 Door
的构造函数,然后将该新的 Door
对象传递给 House
。
After listening to the Clean Code Talks, I came to understand that we should use factories to compose objects. So, for example, if a House
has a Door
and a Door
has a DoorKnob
, in HouseFactory
we create a new DoorKnob
and pass it to the constructor of Door
, and then pass that new Door
object to the constructor of House
.
但是使用 House
(假设类名称为 ABC
)?这取决于 HouseFactory
,对吧?那么我们是否在 ABC
的构造函数中传递 HouseFactory
?
But what about the class that uses the House
(say the class name is ABC
)? It will depend on the HouseFactory
, right? So do we pass the HouseFactory
in the constructor of ABC
? Won't we have to pass a whole lot of factories in the constructor that way?
推荐答案
停留在Door and DoorKnob示例中,我们是否需要在构造函数中传递大量工厂? ,您不需要注入工厂-您可以注入DooKnob本身:
Staying with the Door and DoorKnob example, you don't inject a factory - you inject the DooKnob itself:
public class Door
{
private readonly DoorKnob doorKnob;
public Door(DoorKnob doorKnob)
{
if (doorKnob == null)
throw new ArgumentNullException("doorKnob");
this.doorKnob = doorKnob;
}
}
在此级别上看不到任何工厂。
No factories are in sight in this level.
另一方面,房屋取决于门,而不取决于门把手:
House, on the other hand, depends on Door, but not on DoorKnob:
public class House
{
private readonly Door door;
public House(Door door)
{
if (door == null)
throw new ArgumentNullException("door");
this.door = door;
}
}
这将使选项保持打开状态,直到最后您必须组成应用程序的组成根:
This keeps options open until at last you have to compose everything in the application's Composition Root:
var house = new House(new Door(new DoorKnob()));
您可以使用DI容器在此级别进行撰写,但不必这样做。没有工厂参与。
You can use a DI Container to compose at this level, but you don't have to. No factories are involved.
这篇关于构造函数注入-我们是否也注入工厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!