Dependency Injection in .NET
Ad
What is Dependency Injection?
Dependency Injection (DI) means a class receives its dependencies from outside rather than creating them. .NET has DI built in, making code testable and loosely coupled.
The Problem DI Solves
// ❌ Tight coupling — hard to test
public class OrderService {
private EmailSender _email = new EmailSender();
}
// ✅ Injected — swap implementations easily
public class OrderService {
private readonly IEmailSender _email;
public OrderService(IEmailSender email) { _email = email; }
}
Registering Services
builder.Services.AddScoped<IEmailSender, EmailSender>();
builder.Services.AddSingleton<IConfig, Config>();
builder.Services.AddTransient<IHelper, Helper>();
Service Lifetimes
| Lifetime | Instance |
|---|---|
| Singleton | One for the whole app |
| Scoped | One per request |
| Transient | New every time |
FAQs
Why use interfaces with DI?
So you can swap real implementations for mocks in tests. More in our .NET guides.
Which lifetime should I default to?
Scoped for most services in web apps.
