ASP.NET Core Interview Question #11

What is dependency injection in ASP.NET Core?

ASP.NET Core Fundamentals Junior Beginner

Quick Interview Answer

Dependency injection is a design technique in which a class receives the services it depends on instead of constructing those services itself. ASP.NET Core includes a built-in dependency injection container.

Detailed Explanation

Dependency injection is a design technique in which a class receives the services it depends on instead of constructing those services itself. ASP.NET Core includes a built-in dependency injection container.

Services are registered in IServiceCollection and resolved by the framework when controllers, middleware, Razor Pages, or other registered services are created.

DI reduces coupling, improves testability, centralizes object lifetime management, and makes implementations easier to replace.

Code Example

builder.Services.AddScoped<IOrderService, OrderService>();

public class OrdersController : Controller
{
    private readonly IOrderService _orders;

    public OrdersController(IOrderService orders)
    {
        _orders = orders;
    }
}