0% found this document useful (0 votes)
51 views10 pages

Dependency Injection

Uploaded by

karunjsiruthai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views10 pages

Dependency Injection

Uploaded by

karunjsiruthai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

AmigosKazz

Dependency
injection
Dependency Injection is
a “design pattern” which
consists of separating
the instantiation (and
therefore the
implementation) of a
dependency and its use.

Design Patterns are powerful tools


for software developers, providing
proven solutions to common
design problems.
What's the problem with
dependencies? Why
should they be reduced?
When components are tightly
coupled, a change in one
component may require
changes in other components.
This makes the code difficult to
maintain and evolve.
Objects of type A depend on an object of type B if at
least one of the following conditions is true:

A has an attribute of type B (dependence by


composition);
A is type B (dependence by inheritance);
A depends on another object of type C which
depends on an object of type B (dependence by
transitivity);
a method of A calls a method of B.

If A depends on B, this implies that


to create A, we need B which, in
practice, is not always the case.
Discover the advantage
of Dependency Injection :

Modularisation
Improve Maintainability
Testability
Reusability
Centralized Configuration
Example :

We will see the problems with this approach.


Problems with this Approach :

1. Tight Coupling: “OrderService” is tightly coupled


to “OrderRepository”. If we want to change how orders
are stored (e.g., by using a different database), we
need to modify “OrderService”.
2. Testing Difficulty: Testing “OrderService” in
isolation is difficult because it creates a concrete
instance of “OrderRepository”. We cannot easily inject
a mock or stub of “OrderRepository”.
3. Lack of Flexibility: Adding a new
implementation of “OrderRepository” (e.g., for testing
or specific versions) requires changes in
“OrderService”.
Solution with Dependency
Injection (DI) :
Explaination :

Now “OrderService” depends on the “IOrderRepository”


interface and not the direct “OrderRepository”
implementation. This means we can inject any
implementation of “IOrderRepository“ into
“OrderService”, making our code more flexible and
easier to test.
What do you think of
“dependency injection” ?
Share your experiences in the
comments below! 😅

AmigosKazz

Don’t foreget to share Save This Post

You might also like