ASP.NET Core Interview Question #60

What is constructor injection?

Dependency Injection & Services Junior Beginner

Quick Interview Answer

Constructor injection supplies dependencies through a class constructor. It is the most common DI technique in ASP.NET Core and is generally preferred for required dependencies.

Detailed Explanation

Constructor injection supplies dependencies through a class constructor. It is the most common DI technique in ASP.NET Core and is generally preferred for required dependencies.

Constructor parameters clearly document what a class needs in order to work. They also make dependencies easy to replace during unit testing.

A class with an excessive number of constructor dependencies can indicate that it has too many responsibilities and may need refactoring.

Code Example

public class ReportsController : Controller
{
    private readonly IReportService _reports;
    private readonly ILogger<ReportsController> _logger;

    public ReportsController(
        IReportService reports,
        ILogger<ReportsController> logger)
    {
        _reports = reports;
        _logger = logger;
    }
}