Constructor Injection & Interfaces
Apply constructor injection with interface-based design to decouple components and enable unit testing.
Constructor Injection Basics
Constructor injection is the most common DI pattern. A class declares its dependencies as constructor parameters, and the container provides them at instantiation time.
This makes dependencies explicit, required, and visible.
Defining the Interface
Start with an interface that defines the contract. This allows different implementations (real, mock, in-memory) to be swapped without changing dependent code.
public interface IProductRepository
{
Task<Product?> GetByIdAsync(int id);
Task<IEnumerable<Product>> GetAllAsync();
Task AddAsync(Product product);
}All lessons in this course
- DI Container Fundamentals
- Service Lifetimes: Transient, Scoped, Singleton
- Constructor Injection & Interfaces
- Factory & Options Patterns