ASP.NET Core Interview Question #74

How can extension methods organize service registrations?

Dependency Injection & Services Junior Beginner

Quick Interview Answer

Extension methods can group related IServiceCollection registrations and keep Program.cs readable as an application grows.

Detailed Explanation

Extension methods can group related IServiceCollection registrations and keep Program.cs readable as an application grows.

For example, application services, persistence services, authentication, and external integrations can each have a dedicated Add... extension method. Program.cs then acts as a clear composition root showing the major subsystems.

Registration methods should have descriptive names and should not hide surprising behavior. Over-fragmenting a small application into many extension methods can make configuration harder to trace.

Code Example

public static class DependencyInjection
{
    public static IServiceCollection AddApplicationServices(
        this IServiceCollection services)
    {
        services.AddScoped<IOrderService, OrderService>();
        services.AddScoped<IProductService, ProductService>();

        return services;
    }
}

// Program.cs
builder.Services.AddApplicationServices();