Introducing dependency injection
Dependency injection (DI) is a design pattern used to implement Inversion of Control (IoC) to resolve dependencies in a program. Traditionally, the flow of control is dictated by your code, as it makes calls to reusable libraries or frameworks to use their functionality. IoC inverts this control so that the framework controls it instead.
For example, ASP.NET Core uses DI for IoC extensively. The framework controls the flow of request processing, and the developer’s code is executed in response to specific events like HTTP GET
or POST
requests.
The main idea of DI is to decouple the creation of an object’s dependencies from its own behavior, which allows for more modular, testable, and maintainable code. Instead of objects creating dependencies themselves, they are injected with their dependencies at runtime, often by an external framework or container.
For example, in Figure 10.1, on the left, you can see a statement that...