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 (); } }
Enter fullscreen mode
Exit fullscreen mode
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…