Advertisement
Beginner .NET, Dependency Injection

What is dependency injection, and how does ASP.NET Core's built-in DI container support it?

Short answer

Dependency injection is a design pattern where a class receives its dependencies (other objects it needs to function) from an external source rather than creating them itself, promoting loose coupling and testability.

Save .NET mock interview
Advertisement
AModel answer
Dependency injection is a design pattern where a class receives its dependencies (other objects it needs to function) from an external source rather than creating them itself, promoting loose coupling and testability. ASP.NET Core includes a built-in DI container (IServiceProvider) where you register service implementations against interfaces at startup, and the framework automatically resolves and injects the correct implementation wherever a constructor requests that interface.
public interface IEmailSender { Task SendAsync(string to, string body); }
public class SmtpEmailSender : IEmailSender { ... }

builder.Services.AddScoped<IEmailSender, SmtpEmailSender>();

public class OrderService {
    private readonly IEmailSender _emailSender;
    public OrderService(IEmailSender emailSender) => _emailSender = emailSender;  // auto-injected
}
Real-world example
A checkout service depends on IEmailSender rather than a concrete SmtpEmailSender, letting unit tests inject a fake implementation and letting the real application swap SMTP providers without changing OrderService's code at all.
Likely follow-ups
  • What are the three built-in service lifetimes and how do they differ?
  • How does DI relate to the broader Inversion of Control principle?
Related topics