Junior — Middle
How is the dependency injection concept related to the inversion of control principle in programming?
sobes.tech AI
Answer from AI
Dependency Injection (DI) is a specific way of implementing the Inversion of Control (IoC) principle.
The Inversion of Control principle means that the creation and binding of objects are delegated to an external container or framework, rather than being implemented within the classes themselves.
Dependency injection is when the necessary objects (dependencies) are passed to a class from outside, usually through a constructor, setter, or interface, instead of the class creating them itself.
For example:
class Service {
private Repository repo;
// Injecting dependency via constructor
public Service(Repository repo) {
this.repo = repo;
}
}
Thus, DI implements IoC, making the code more flexible, testable, and loosely coupled.