Inversion of Control and Dependency Injectionโ
In this section, we will explore the principles of Inversion of Control (IoC) and Dependency Injection (DI).
What is Inversion of Control?โ
Inversion of Control is a principle in software engineering which transfers the control of objects or portions of a program to a container or framework. We most often use it in the context of object-oriented programming.
In contrast with traditional programming, in which our custom code makes calls to a library, the IoC enables a framework to take control of the flow of a program and make calls to our custom code. To enable this, frameworks use abstractions with additional behavior built in.
The advantages of this architecture are:
- Decoupling the execution of a task from its implementation
- Making it easier to switch between different implementations
- Greater modularity of a program
- Greater ease in testing a program by isolating a component or mocking its dependencies and allowing components to communicate through contracts
One of the ways you can achieve Inversion of Control is a Dependency Injection (DI).
What is Dependency Injection?โ
Dependency injection is a pattern you can use to implement IoC, where the control being inverted is setting an object's dependencies.
Connecting objects with other objects, or โinjectingโ objects into other objects, is done by an assembler rather than by the objects themselves.
Here's how you would create an object dependency in traditional programming:
class Store {
private item: Item;
constructor() {
this.item = new ItemImpl();
}
}
By using DI, you can rewrite the example without specifying the implementation of the Item that we want:
class Store {
constructor(
private item: Item
) {}
}