Dependency Injection Explained in .NET

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 :

Dependency Injection Explained in .NET

Example No 2 :

Dependency Injection Explained in .NET

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:

Dependency Injection Explained in .NET

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place