Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to .NET
Dependency Injection in .NET

Dependency Injection in .NET

.NET2,914 viewsBy Admin
dot-netdependencyinjection

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

LifetimeInstance
SingletonOne for the whole app
ScopedOne per request
TransientNew 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.