Dependency injection (DI) in ASP.NET Core is not an add-on: it is a first-class citizen. The container comes built-in from day one and is part of the application’s very startup sequence.
When used well, our applications become much easier to:
- Maintain
- Test
- Understand (separation of concerns)
- Scale
But when used incorrectly… the problems can be silent and expensive: memory leaks, hard-to-reproduce race conditions, circular dependencies, and services that end up tightly coupled without us even realizing it.
In this post, I will share 12 practical rules that I have seen make all the difference in real-world projects (and that I try to follow myself to avoid future headaches).
First, let’s understand lifetimes (very quickly)
ASP.NET Core manages three primary service lifetimes, and the order matters a lot:
Singleton → Scoped → Transient
In other words: a service with a longer lifetime should never depend on one that lives for a shorter time.
Golden rule: a service should only depend on services that have the same or a longer lifetime than itself in that hierarchy. If you break this rule, the classic captive dependency problem appears, and it tends to hurt significantly once discovered in production.
1. Transient for lightweight, stateless services
services.AddTransient<IEmailFormatter, EmailFormatter>();
When to choose Transient:
- Helpers, formatters, mappers
- Purely functional services (stateless)
- Quick, inexpensive operations
Every time a component requests it, a new instance is created.
Watch out: if the constructor performs heavy work (reading large files, expensive initial connections, etc.) or if it is resolved hundreds of times per request… think twice.
2. Scoped for everything that should live “during an HTTP request”
services.AddScoped<IOrderService, OrderService>();
The star use case is Entity Framework Core’s DbContext:
services.AddDbContext<AppDbContext>();
Scoped guarantees that throughout the entire HTTP request, you will have the exact same instance. This is crucial for maintaining consistency across transactions, change tracking, etc.
Never register a DbContext as a Singleton. It is one of the fastest ways to break an application in production.
3. Singleton only when it is truly safe
services.AddSingleton<ICacheService, MemoryCacheService>();
A Singleton lives for the entire lifetime of the application. Therefore:
- It must be thread-safe (or properly synchronize anything it touches)
- It must not hold state specific to a user or a request
- It must never depend on Scoped services
A good candidate for a Singleton is usually a completely stateless service or one that safely manages shared resources (such as caching).
If you introduce a Singleton that is not thread-safe or that captures shorter-lived dependencies… prepare for intermittent headaches that are a nightmare to debug.
4. Always inject interfaces, never concrete implementations
Good:
public class OrderService : IOrderService
{
private readonly IPaymentGateway _gateway;
public OrderService(IPaymentGateway gateway)
{
_gateway = gateway;
}
}
Bad (avoid this):
public OrderService(PaymentGateway gateway) { … }
Injecting the interface reduces coupling and allows you to easily create mocks in unit tests. It is one of the fundamental reasons “why we use DI” in the first place.
5. If the constructor looks like a grocery list, something smells
Suspicious example:
public OrderService(
IRepository repo,
ILogger logger,
IMapper mapper,
ICache cache,
IValidator validator,
IEmailService email)
{ … }
When a constructor receives 5–7 dependencies (or more), you are almost certainly violating the Single Responsibility Principle (SRP).
Before adding the next dependency, pause and ask yourself:
“Is this class doing too many things? Could I split it into two smaller, more focused services?”
6. Never, ever inject a Scoped service into a Singleton
This is probably the #1 mistake I see in code reviews and production incidents.
If a Singleton captures a Scoped service, you break the lifetime hierarchy -> captive dependency.
- Best-case scenario -> startup exception (if validation is enabled)
- Worst-case scenario -> stale data, memory leaks, or unpredictable behavior that only surfaces under actual load
Avoid it at all costs.
7. When you genuinely need a Scoped service inside a Singleton… use IServiceScopeFactory
Common in BackgroundService, Hosted Services, background processors, etc.:
public class Worker : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
public Worker(IServiceScopeFactory scopeFactory)
{
_scopeFactory = scopeFactory;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var scope = _scopeFactory.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// tu lógica aquí, dentro del scope correcto
}
}
This way, you create an “artificial” scope exclusively for that execution, keeping everything within its proper lifetime.
8. Don’t let Program.cs turn into a 300-line monster
Instead of registering everything there, organize registrations using extension methods:
builder.Services.AddInfrastructureServices();
builder.Services.AddApplicationServices();
builder.Services.AddDomainServices();
Example:
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddInfrastructureServices(this IServiceCollection services)
{
services.AddScoped<IRepository, Repository>();
services.AddSingleton<ICacheService, MemoryCacheService>();
// ...
return services;
}
}
Your Program.cs stays clean, readable, and much easier to maintain as the project grows.
9. Enable container validation (at least in development)
builder.Host.UseDefaultServiceProvider(options =>
{
options.ValidateScopes = true;
options.ValidateOnBuild = true;
});
This automatically detects:
- Circular dependencies
- Captive dependencies
- Incorrectly registered services
It is infinitely better for the application to warn you during local startup than discovering the issue at 3 AM in production.
10. Forget about Service Locator (GetService / GetRequiredService outside the constructor)
Bad (very bad):
var service = provider.GetService<IOrderService>();
This hides real dependencies, makes testing significantly harder, and works directly against the philosophy of DI.
Whenever possible: constructor injection. It is more explicit, and the compiler helps you.
11. Hunt down circular dependencies from day one
If A needs B and B needs A… the container chokes and cannot construct the graph.
This is usually a sign that the design needs a review. A few quick solutions:
- Extract the shared responsibility into a third service
- Create a “bridge” interface or an event
- Use patterns like Mediator / CQRS when the domain justifies it
12. Use IOptions (and its variants) for strongly typed configuration
Instead of injecting IConfiguration directly and calling .GetSection("MySettings") all over the place:
public class MyService
{
private readonly MySettings _settings;
public MyService(IOptions<MySettings> options)
{
_settings = options.Value;
}
}
Useful variants depending on the scenario:
IOptions-> static configuration (the most common)IOptionsSnapshot-> reloaded on every request (useful if you need changes without restarting)IOptionsMonitor-> singleton that allows subscribing to real-time changes
Typing your configuration drastically improves readability and eliminates silly typos in key names.
Most common production mistakes (quick summary)
- Singletons capturing Scoped dependencies (the classic)
- Transient used on heavy objects instantiated 1,000 times per second
- “God” classes with 12 dependencies and 400 lines
- Using Service Locator “because it is faster to type”
- DbContext as a Singleton (please, don’t)
Wrapping up
Dependency injection is not merely “a cool way to avoid the new keyword.” It is one of the most powerful levers you have to keep your code maintainable, testable, and scalable as the project expands.
If you respect lifetimes, keep classes focused, avoid dangerous shortcuts, and validate early… you will end up with much healthier applications that are far easier to evolve.
Well-used DI goes unnoticed.
Poorly-used DI… turns into constant pain.
Better to get it right from the start.
Which of these 12 rules has bitten you the most in past projects? Or which one do you apply religiously? Feel free to leave a comment—I’d love to read your real-world experiences.
Let’s keep coding.