Different Ways to Inject Dependencies in .NET Core



It is impossible nowadays to design classes/controllers which don’t depend on other objects. Rather than instantiating those objects inside other objects directly, it is a good practice to register them once and then use them as needed. This improves testability and maintenance due to loose coupling. You would realize this benefit when you write mock tests and have different implementations. In this article, we will see three different ways you can inject dependencies and also look into pitfalls to avoid memory leaks.


Using Constructor Injection

This is the most common way of resolving dependencies. Below is an interface to implement a custom logger.



Now let’s create a concrete class that implements the above interface.



Register above class in Program.cs file as a scoped service.