Dependency Injection (DI) is a core concept in .NET since .NET Core, and it's the default pattern used in ASP.NET Core apps, console apps, and even workers or background services.
Whether you're building a web API or a desktop tool, mastering DI leads to cleaner, testable, and maintainable code.
1. What is Dependency Injection?
Dependency Injection is a design pattern where.
- A class doesn't create its dependencies.
- Instead, they are "injected" from outside (via constructors or setters).
This follows Inversion of Control (IoC), where the control of creating objects is inverted and handled by a container.
Without DI
public class ReportService
{
private readonly EmailSender _emailSender = new EmailSender(); // tightly coupled
}
With DI
public class ReportService
{
private readonly IEmailSender _emailSender;
public ReportService(IEmailSender emailSender)
{
_emailSender = emailSender;
}
}
2. Setting Up Dependency Injection in .NET
DI in .NET is handled by the built-in service container via IServiceCollection.
In a .NET Core or .NET 6+ app, services are registered in Program.cs.
Example
var builder = WebApplication.CreateBuilder(args);
// Registering services
builder.Services.AddTransient<IEmailSender, EmailSender>();
builder.Services.AddScoped<IReportService, ReportService>();
var app = builder.Build();
app.MapGet("/", (IReportService reportService) =>
{
reportService.GenerateReport();
return "Report Generated!";
});
app.Run();
3. Types of Dependency Injection
Constructor Injection (most common)
public class ReportService
{
private readonly IEmailSender _emailSender;
public ReportService(IEmailSender emailSender)
{
_emailSender = emailSender;
}
}
Method Injection
public class NotificationService
{
public void Notify(IEmailSender sender)
{
sender.Send("Hello!");
}
}
Property Injection (less preferred)
public class OrderService
{
public IEmailSender EmailSender { get; set; }
}
4. Service Lifetimes Explained
When registering services, choose an appropriate lifetime.
Join the conversation! Your thoughts help the community grow.