In this article, I will share my experiences and suggestions on using Dependency Injection in ASP.NET Core applications. The motivation behind these principles are;
- Effectively designing services and their dependencies.
- Preventing multi-threading issues.
- Preventing memory-leaks.
- Preventing potential bugs.
This article assumes that you are already familiar with Dependency Injection and ASP.NET Core in a basic level. If not, please read the ASP.NET Core Dependency Injection documentation first.
Basics
Constructor Injection
Constructor injection is used to declare and obtain dependencies of a service on the service construction. Example:
public class ProductService
{
private readonly IProductRepository _productRepository; public ProductService(IProductRepository productRepository)
{
_productRepository = productRepository;
} public void Delete(int id)
{
_productRepository.Delete(id);
}
}
ProductService is injecting IProductRepository as a dependency in its constructor then using it inside the Delete method.
Good Practices:
- Define required dependencies explicitly in the service constructor. Thus, the service can not be constructed without its dependencies.
- Assign injected dependency to a read only field/property (to prevent accidentally assigning another value to it inside a method).
Property Injection
ASP.NET Core’s standard dependency injection container does not support property injection. But you can use another container supporting the property injection. Example:
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstracti