我正在学习 C# 及其相关的最佳实践。
现在我知道了:
- 单一职责原则
- 静态类
- 单例
- 依赖注入(inject)
每个人都说要避免 Singleton 和 Static,而更喜欢依赖注入(inject)。
现在我已经转换了我所有的类,这样他们就不必获取自己的数据,例如删除:
_myItem = Repository.Instance.FindById(1);
而是将我的依赖项注入(inject)到 MyClass 中。
public MyClass(Repository repository) {
_myItem = repository.FindById(1);
}
但是,既然 MyClass 遵循单一职责原则,并从 MyClass 外部获取所有依赖项,那么哪个/哪个类将负责提供所有依赖项?
我在 Unity 中的示例问题是:
- UIStatusPanelClass 依赖于 CurrentCharacter。
- GameInputClass 依赖于 CurrentCharacter 和 CurrentCamera。
- CharacterManagerClass 持有 CurrentCharacter,但不负责传递给其他类,因为它的唯一职责是持有场景中的所有角色。
- UIInventoryClass 依赖于由 CurrentCharacter 持有的 InventoryClass。
- StatisticClass 取决于 CurrentCharacter。
- ItemRepositoryClass 负责保存 List 但不负责获取项目。
请帮我整理一下我对这些东西的认识。
最佳答案
now that MyClass following Single Responsibility Principle, and getting all dependencies from outside MyClass, what/which class will be responsible to giving all the dependencies?
这是Composition Root的函数:
A Composition Root is a (preferably) unique location in an application where modules are composed together.
组合根位于应用程序根内。
DI 容器是一种有用但可选的工具,可以充当合成引擎。在没有 DI 容器的情况下应用 DI 是一种称为 Pure DI 的做法.如果您使用 DI 容器,它可以被视为您的 Composition Root 的一部分。
关于以下代码的一个警告:
public MyClass(Repository repository) {
_myItem = repository.FindById(1);
}
练习DI时,注入(inject)构造函数应该没有任何逻辑,应该做nothing more than just store their incoming dependencies .这意味着您不应从 MyClass
的构造函数中调用 FindById
。这应该在稍后阶段完成;在 MyClass
的方法之一中。
关于c# - 所有(OOP)依赖项的根存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57507566/