是否可以进行不会导致控制反转的依赖注入?

is it possible to do dependency injection that doesn't result in Inversion of Control?

首先,我是软件界的新手。如果这是一个简单或糟糕的问题,我深表歉意。

我一直在阅读有关 DI 和 IOC 的文章,我了解到 DI 是实现 IOC 的一种方式(还有其他方式)。所以我一直在想,DI 是否总是导致控制反转?这取决于您如何调用受益于 DI 的方法或 类 吗?也就是说,你的应用程序的流程将决定DI是否会导致IOC,对吗?

我认为 Dependency Injection Principles, Practices, and Patterns (DIPP&P) 的这句话非常概括:

Dependency Injection or Inversion of Control?

The term Inversion of Control originally meant any sort of programming style where an overall framework or runtime controlled the program flow. According to that definition, most software developed on the .NET Framework uses IoC. When you write an ASP.NET Core MVC application, for instance, you create controller classes with action methods, but it’s ASP.NET Core that will be calling your action methods. This means you aren’t in control — the framework is.

These days, we’re so used to working with frameworks that we don’t consider this to be special, but it’s a different model from being in full control of your code. This can still happen for a .NET application, most notably for command-line executables. As soon as Main is invoked, your code is in full control. It controls program flow, lifetime — everything. No special events are being raised and no overridden members are being invoked.

Before DI had a name, people started to refer to libraries that manage Dependencies as Inversion of Control Containers, and soon, the meaning of IoC gradually drifted towards that particular meaning: Inversion of Control over Dependencies. Always the taxonomist, Martin Fowler introduced the term Dependency Injection to specifically refer to IoC in the context of dependency management. Dependency Injection has since been widely accepted as the most correct terminology. In short, IoC is a much broader term that includes, but isn’t limited to, DI.

[source: Section 1.4.1, page 29. Online version]

这句话是在 .NET 的背景下写的,但如果你过滤掉 .NET 和 ASP.NET,它的适用范围很广。在 Martin Fowler 最初的定义中,IoC 是关于框架的,而 DI 本身可以在没有任何框架的情况下应用,例如使用 'simple' (UI-less) 控制台应用程序。这意味着,根据 Fowler 最初的定义,可以在不应用 IoC 的情况下练习 DI。

然而,多年来,IoC 一词已经“漂移”,我们现在通常将 DI 视为 IoC 的特殊形式。可以说是“子类型”或“实现”,其中 IoC 是概念或“抽象”。这意味着没有IoC就不能应用DI,因为练习DI就是练习IoC。但是,您可以在不练习 DI 的情况下练习 IoC,因为还有其他 IoC 实现,例如服务定位器。