Dependency injection in C#, explained with one example
Dependency injection (DI) sounds complicated, but the idea is simple:
A class shouldn’t build the things it needs. It should be given them.
Think of a coffee shop. The barista doesn’t go out and build an espresso machine every morning. The machine is supplied, and the barista just uses it. If the shop swaps it for a better one, the barista still makes coffee the same way.
Here’s one example in C#, from start to finish.
The problem: a class that builds its own tools
An OrderService needs to send a confirmation when an order is placed:
public class OrderService
{
public void PlaceOrder(string customerEmail)
{
// ...save the order...
var sender = new EmailSender(); // builds its own dependency
sender.Send(customerEmail, "Thanks for your order!");
}
}
This works, but OrderService is now welded to EmailSender:
- Want to send an SMS instead? You have to edit
OrderService. - Want to unit test
PlaceOrder? Every test sends a real email.
The fix: ask for it, don’t build it
Step 1: describe what you need with an interface. OrderService doesn’t care how the message is sent, only that it can be:
public interface IMessageSender
{
void Send(string to, string message);
}
public class EmailSender : IMessageSender
{
public void Send(string to, string message) =>
Console.WriteLine($"Email to {to}: {message}");
}
Step 2: receive it through the constructor. This is the “injection”:
public class OrderService(IMessageSender sender)
{
public void PlaceOrder(string customerEmail)
{
// ...save the order...
sender.Send(customerEmail, "Thanks for your order!");
}
}
OrderService no longer mentions EmailSender anywhere. It just says “give me something that can send a message”.
Step 3: tell .NET what to hand over. In Program.cs, register which class fills the interface:
builder.Services.AddScoped<IMessageSender, EmailSender>();
builder.Services.AddScoped<OrderService>();
From now on, whenever something asks for an OrderService, .NET creates it and passes in an EmailSender automatically. In a Web API, you just ask for it in your endpoint:
app.MapPost("/orders", (string email, OrderService orders) =>
{
orders.PlaceOrder(email);
return Results.Ok();
});
The payoff
Swapping is a one-line change. Switching to SMS means writing an SmsSender : IMessageSender and changing the registration. OrderService is untouched:
builder.Services.AddScoped<IMessageSender, SmsSender>();
Testing becomes easy. In a unit test, you hand OrderService a fake sender that just records what it was asked to do. No real emails:
public class FakeSender : IMessageSender
{
public List<string> Sent { get; } = [];
public void Send(string to, string message) => Sent.Add(to);
}
[Fact]
public void PlaceOrder_sends_a_confirmation()
{
var fake = new FakeSender();
var service = new OrderService(fake);
service.PlaceOrder("jo@example.com");
Assert.Single(fake.Sent);
}
In one sentence
Instead of a class creating what it needs with new, it asks for it in its constructor, and .NET supplies it, so you can swap the real thing for another version, or a fake in tests, without touching the class.
Sources
- Dependency injection in .NET — Microsoft Learn
- Dependency injection in ASP.NET Core — Microsoft Learn