c# - 所有(OOP)依赖项的根存储在哪里?

标签 c# .net oop unity3d dependency-injection

我正在学习 C# 及其相关的最佳实践。

现在我知道了:

  1. 单一职责原则
  2. 静态类
  3. 单例
  4. 依赖注入(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/

相关文章:

c# - 在动态 View 中隐藏模型的属性

c# - 高效的异常处理技术

c# - ASP.Net 模拟方法的差异

language-agnostic - "program to an interface"是什么意思?

c# - 有没有办法在实例化对象时隐藏/显示某些方法?

c# - 检查属性是否具有特定属性?

c# - 如何将 int 转换为选择的枚举?

c# - 使用 json.NET 和 C# 解析 JSON 数组

c# - 如何在控件中使用 PreLoad 事件?

c# - .NET 2.0等效于C#扩展方法