What is dependency injection
Benefits of dependency injection
Different ways of implementing dependency injection
What is dependency injection?
According to Wikipedia :
Dependency injection is a programming technique in which an object receives other required objects instead of creating them internally.
In simple words, dependency injection is a design pattern where our purpose is to achieve inversion of control b/w classes and their dependencies.
Let’s understand Inversion of Control with an example :
Example No. 1 :
Example No 2 :
StudentService class has a dependency on StudentRepository, in the first example we have hardcoded the objection creation, this version does not follow Inversion of Control.
Then in the second example, we have injected the interface that is responsible for objection creation, this approach is more flexible because now we can add N more dependencies in the StudentRepository and we don’t need to worry about its object creation.
What are the benefits of Dependency Injection?
Let’s understand some benefits in the light of above two examples :
We don’t need to worry about objection creation, it’s not our headache either some class has 1 dependency or 10. It will be handled automatically by a built-in container of .NET
We don’t need to think about disposing of the objects, it will be handled automatically.
We can easily unit test the second example, and it is much more adaptive for new changes without affecting the existing code that much.
Different ways of implementing Dependency Injection
There are three ways of doing that :
Singelton
Scoped
Transient
Singleton: This will create only one instance of the class, which will be used everywhere.
Transient: This will create a new instance of the class every time it is injected.
Scoped: Within a single request, the same instance will be used wherever it is injected. However, once the request ends, those instances will be disposed of.
This is how we register these services with different scopes:
Shoot out: -
Most developers struggle with testing and TDD. To solve this, my friend Daniel Moka just launched his TDD course containing real-world projects and practical lessons to master Test-Driven Development
He gave me 25 exclusive 50% OFF coupon codes just for you.
Use the code 'MUHAM_50' at checkout. Get instant access here
Whenever you’re ready, there are 2 ways I can help you:
Promote yourself to 10400+ subscribers by sponsoring this newsletter
Patreon Community: Join and gain access to the 200+ articles I have published so far in one place. Join here