Sitemap

Dependency Injection and Service Lifetimes in .NET Core

2 min readNov 25, 2020
Press enter or click to view image in full size

⚠️ This article has moved to my website.

You can read the latest version here:
👉 https://henriquesd.com/articles/dependency-injection-and-service-lifetimes-in-net-core

Below is a short preview of the article.

Dependency Injection (DI) is a design pattern which supports the development of loosely coupled code, and it’s also one of the SOLID principles (Dependency Inversion Principle). On this article, I will explain how we can use Dependency Injection and what is the difference between the three services lifetimes that can be used in .NET Core applications.

“Dependency Injection (DI) is a technique that provides dependencies to a class, thereby achieving dependency inversion. Dependencies are passed (injected) to a client that needs it.”

DI is used a lot in .NET Core applications, and also the own framework brings it natively. Using Dependency Injection brings a lot of benefits like:

  • Removes hardcoded dependencies and allows them to be changed
  • Allows the developer to write loosely coupled code, making applications easier to maintain, extend, and test
  • Increase the testability in software applications that use DI. Loosely coupled code can be tested more easily. It’s easier to make a change in the code without affecting other areas of the application. With DI it’s possible to inject mocked dependencies in the tests.
  • Developers can work on different pieces of functionality in parallel since the implementations are independent of each other.
  • Improve the readability and cleanliness of the code

Example of Dependency Injection

On the code below, there is the ICategoryRepository interface and the class CategoryRepository which implements this interface:

The interface is like a contract. So the class who implements this interface should implement all methods that this interface demands. For example, if the CategoryRepository class does not implement the GetCategory method, it will show an error, because the interface demands that this method need to be implemented in the class.

👉 Continue reading the full article here: https://henriquesd.com/articles/dependency-injection-and-service-lifetimes-in-net-core