Inversion of Control (IoC) and Dependency Injection (DI) are related concepts, but they are not the same thing.
Question. Is Dependency Injection the same as Inversion of Control?
Answer: No. IoC is a principle, while DI is one way to implement that principle.
1. What is Inversion of Control (IoC)?
Normally, an object creates and manages its own dependencies.
Without IoC
public class OrderService {
private PaymentService paymentService;
public OrderService() {
paymentService = new PaymentService();
}
public void placeOrder() {
paymentService.processPayment();
}
}
What happens here?
paymentService = new PaymentService();
OrderService is responsible for:
- Creating the dependency
- Managing the dependency
- Using the dependency
The control is inside OrderService
Problem
Suppose tomorrow you want:
CreditCardPaymentService instead of PaymentService
You must modify: OrderService
This creates tight coupling.
IoC Concept
With IoC: Object creation responsibility is moved outside the class.
Instead of: OrderService creates PaymentService
we do:
- Someone else creates PaymentService
- Someone else gives it to OrderService
Control is inverted.
That's why it is called: Inversion of Control
Real-Life Example
Imagine a restaurant.
Without IoC - You go into the kitchen and cook your own food.
Customer --> Kitchen --> Cooks food
Customer controls everything.
With IoC - You sit at the table.
Waiter brings food.
Customer <-- Waiter <-- Kitchen
Customer doesn't control food preparation.
Control has been inverted.
SOCIAL SHARE CARD GENERATOR