ASP.NET Core Interview Question #52

Why is dependency injection important in ASP.NET Core applications?

Dependency Injection & Services Junior Beginner

Quick Interview Answer

Dependency injection separates a class from the concrete construction of its dependencies. Instead of a controller creating repositories, loggers, or services with new, those dependencies are supplied by the container.

Detailed Explanation

Dependency injection separates a class from the concrete construction of its dependencies. Instead of a controller creating repositories, loggers, or services with new, those dependencies are supplied by the container.

This improves maintainability because implementations can change without rewriting every consumer. It also improves unit testing because real dependencies can be replaced with mocks, fakes, or test implementations.

DI additionally gives ASP.NET Core a consistent way to manage object lifetimes and dispose services that implement IDisposable or IAsyncDisposable when their scope ends.

Code Example

public class ProductService
{
    private readonly IProductRepository _repository;

    public ProductService(IProductRepository repository)
    {
        _repository = repository;
    }
}