What is the difference between inversion of control (IoC) and dependency injection?
sobes.tech AI
Answer from AI
Inversion of Control (IoC) is a general design principle according to which the flow of control in a program changes: instead of explicitly managing dependencies and the logic of their invocation, the component relies on an external framework or container that manages this flow.
Dependency Injection (DI) is one of the specific patterns implementing the IoC principle. It involves passing dependencies (objects that the current component depends on) to the component from outside, instead of the component creating or finding them itself.
Thus, DI is a way to achieve IoC.
Main differences:
- IoC — principle/concept.
- DI — pattern/implementation.
- IoC can be implemented in various ways (e.g., factory method, service locator), DI is one of these ways.
- IoC shifts the responsibility for creating and binding objects from the component to the framework/container.
- DI implements this shift by passing dependencies through constructor, setter, or interface.
Example of DI (constructor):
// class dependent on Service
public class Client {
private final Service service;
// Constructor accepts dependency (Service)
public Client(Service service) {
this.service = service;
}
public void doSomething() {
service.execute();
}
}
// Dependency interface
public interface Service {
void execute();
}
// Concrete implementation of dependency
public class ServiceImpl implements Service {
@Override
public void execute() {
System.out.println("Executing service...");
}
}
// Class responsible for "injection"
public class AppConfig {
public static void main(String[] args) {
Service myService = new ServiceImpl(); // Creating dependency
Client client = new Client(myService); // Injecting dependency via constructor
client.doSomething();
}
}
In this example, the Client class does not create ServiceImpl directly. Instead, ServiceImpl is created elsewhere (AppConfig) and passed (injected) into Client via its constructor. This implements the IoC principle, as the creation and binding of Service are inverted — they are not in Client.