What is dependency injection in ASP.NET Core?
Learn how dependency injection reduces coupling and how to choose service lifetimes in ASP.NET Core.
Answer
Dependency injection (DI) is a technique in which a class receives the objects it depends on from an external component instead of constructing those dependencies itself. This improves testability, maintainability, and separation of concerns.
ASP.NET Core includes a built-in service container. Services are registered during application startup and can be injected into constructors or other supported locations.
The common service lifetimes are Transient, Scoped, and Singleton. Transient creates a new instance each time it is requested. Scoped creates one instance per scope, commonly one per HTTP request. Singleton uses one instance for the application's lifetime. A singleton should not directly capture a scoped service because that can cause lifetime and data consistency problems.
Code example
builder.Services.AddScoped<IOrderService, OrderService>();
public sealed class OrdersController : ControllerBase
{
private readonly IOrderService _orders;
public OrdersController(IOrderService orders)
{
_orders = orders;
}
}Key points to remember
- Register services with AddTransient, AddScoped, or AddSingleton.
- Use scoped lifetime for many request-oriented services, such as an EF Core DbContext.
- Keep constructors explicit about their dependencies.
- Be careful with thread safety and lifetime mismatches.
Keep practising
Understanding beats memorization.
Explain the concept in your own words, then think through how you would use it in a real project.
AI-powered mock interview practice is planned for a future release.