What is dependency injection, and how does ASP.NET Core's built-in DI container support it out of the box?
Short answer
Dependency injection is a design pattern where a class receives its dependencies from an external source rather than creating them itself, promoting loose coupling and testability.
Advertisement
AModel answer
Dependency injection is a design pattern where a class receives its dependencies from an external source rather than creating them itself, promoting loose coupling and testability. ASP.NET Core includes a built-in DI container where you register service implementations against interfaces in Program.cs, 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(IEmailSender emailSender) {
// emailSender is automatically 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