SOLID & Design Patterns Interview Question #49

What is the Dependency Injection Pattern in .NET applications?

Structural, Creational & Behavioral Patterns Mid-Level Intermediate

Quick Interview Answer

Dependency Injection supplies a class with its collaborators from the outside rather than letting the class construct those collaborators directly. Constructor injection is the most common form because required dependencies are explicit.

Detailed Explanation

Dependency Injection supplies a class with its collaborators from the outside rather than letting the class construct those collaborators directly. Constructor injection is the most common form because required dependencies are explicit.

ASP.NET Core includes a built-in dependency injection container with transient, scoped, and singleton lifetimes. Choosing the correct lifetime is important, especially when services depend on scoped resources such as DbContext.

Code Example

builder.Services.AddScoped<IOrderRepository,
    OrderRepository>();

builder.Services.AddScoped<OrderService>();

public OrderService(IOrderRepository repository)
{
    _repository = repository;
}