Menu

1 / 2

What's the difference IoC and Dependency Injection?

DEV Community: java·Tapas Pal·5 months ago
#AY8ZpTZN
Reading 0:00
15s threshold

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…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.