ASP.NET Core Interview Question #51

What is dependency injection in ASP.NET Core?

Dependency Injection & Services Junior Beginner

Quick Interview Answer

Dependency injection (DI) is a design technique in which a class receives the objects it depends on instead of creating those objects itself. ASP.NET Core includes a built-in dependency injection container.

Detailed Explanation

Dependency injection (DI) is a design technique in which a class receives the objects it depends on instead of creating those objects itself. ASP.NET Core includes a built-in dependency injection container.

Services are registered in IServiceCollection during application startup. The framework then resolves those services when it creates controllers, middleware, Razor Pages, background services, or other registered classes.

DI reduces tight coupling, centralizes lifetime management, improves testability, and makes implementations easier to replace. Constructor injection is the most common and recommended form for required dependencies.

Code Example

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

public class OrdersController : Controller
{
    private readonly IOrderService _orderService;

    public OrdersController(IOrderService orderService)
    {
        _orderService = orderService;
    }
}