ASP.NET Core Interview Question #64

How do you register a concrete service without an interface?

Dependency Injection & Services Junior Beginner

Quick Interview Answer

ASP.NET Core can register a concrete class directly. This is useful when there is only one meaningful implementation and an interface would not provide a useful abstraction.

Detailed Explanation

ASP.NET Core can register a concrete class directly. This is useful when there is only one meaningful implementation and an interface would not provide a useful abstraction.

The same lifetime rules apply. A consumer requests the concrete class in its constructor, and the DI container creates it.

Interfaces are valuable at architectural boundaries and when multiple implementations or test substitutions are expected, but creating an interface for every class is not required.

Code Example

builder.Services.AddScoped<InvoiceCalculator>();

public class BillingService
{
    private readonly InvoiceCalculator _calculator;

    public BillingService(InvoiceCalculator calculator)
    {
        _calculator = calculator;
    }
}