ASP.NET Core Interview Question #75
What are good dependency injection practices in ASP.NET Core?
Dependency Injection & Services Junior Beginner
Quick Interview Answer
Use constructor injection for required dependencies, choose lifetimes deliberately, and keep singleton services thread-safe. Avoid injecting scoped services into singletons and avoid using IServiceProvider as a general-purpose service locator.
Detailed Explanation
Use constructor injection for required dependencies, choose lifetimes deliberately, and keep singleton services thread-safe. Avoid injecting scoped services into singletons and avoid using IServiceProvider as a general-purpose service locator.
Prefer abstractions where they represent meaningful boundaries or multiple implementations, but do not create interfaces mechanically for every class. Group related registrations clearly, validate required configuration, and keep service construction separate from business logic.
Also watch for constructors with too many dependencies. They often indicate that a class has accumulated too many responsibilities. DI should make dependencies explicit; it should not be used to hide poor object design.
Code Example
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddApplicationServices();
builder.Services.AddInfrastructure(builder.Configuration);
var app = builder.Build();