C# Interview Question #161
How does dependency injection work in ASP.NET Core?
ASP.NET Core, DI & Middleware Senior Advanced
Quick Interview Answer
ASP.NET Core includes a built-in dependency injection container. Services are registered in IServiceCollection during application startup and are resolved from IServiceProvider when required.
Detailed Explanation
ASP.NET Core includes a built-in dependency injection container. Services are registered in IServiceCollection during application startup and are resolved from IServiceProvider when required.
Constructor injection is the most common approach. A controller or service declares its dependencies in its constructor, and the framework supplies registered implementations.
DI improves separation of concerns, testability, lifetime management, and loose coupling. Services should generally depend on abstractions when a meaningful abstraction boundary exists.
Code Example
builder.Services.AddScoped<IProductService, ProductService>();
public class ProductsController : Controller
{
private readonly IProductService _service;
public ProductsController(IProductService service)
{
_service = service;
}
}