6.9 — Constructor Injection vs [FromServices] vs Service Locator¶
← Roadmap · Section: 6. Dependency Injection Prev: 6.8 Factories and open generics · Next: 6.10 Disposal
Markers: ⭐ ⚠️ · Confidence: 🔴 · Last reviewed: —
TL;DR¶
Three ways to get a dependency, in descending order of preference.
- Constructor injection — the default. The constructor is an honest list of what the class needs.
[FromServices]— inject into a single action method. Useful when only one action needs it.- Service locator — injecting
IServiceProviderand pulling services out. An anti-pattern, with narrow exceptions.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Constructor injection | the main style | Dependencies arrive as constructor parameters. Resolved when the object is built. |
| Method injection | a style | Dependencies arrive as method parameters. Used by middleware's InvokeAsync. |
[FromServices] |
an attribute | Marks an action parameter to come from DI rather than the request. |
| Service locator | an anti-pattern | A class asks the container for what it needs, instead of declaring it. |
IServiceProvider |
an interface | The container. Injecting it into your classes is the service locator smell. |
| Hidden dependency | a design problem | A dependency not visible in the class's public surface. |
| Explicit dependencies principle | a design rule | A class should state everything it needs in its constructor. |
ActivatorUtilities |
a static class | Builds an object with DI plus runtime arguments. See 6.8. |
The concept¶
Why the constructor is the right place¶
public class OrderService(
IOrderRepository repo,
IEmailSender email,
ILogger<OrderService> logger)
{
// ...
}
Read that constructor and you know everything this class depends on. Four benefits follow:
It is honest. Nothing is hidden. A reviewer sees the full list without reading the body.
It fails early. A missing registration throws when the object is built — and with
ValidateOnBuild, at application startup (6.2).
It is testable. Construct it with fakes. No container involved.
It is a design signal. Eight parameters means the class does eight things. That pressure is useful — it pushes you to split the class.
A picture: a job application that lists your requirements up front, versus one where you turn up and start asking for things you forgot to mention.
The alternative that looks convenient¶
public class OrderService(IServiceProvider provider)
{
public async Task CompleteAsync(Guid id, CancellationToken ct)
{
var repo = provider.GetRequiredService<IOrderRepository>();
var email = provider.GetRequiredService<IEmailSender>();
// ...
}
}
This works. It is also worse in every way that matters:
Dependencies are invisible. The constructor says the class needs "the container", which is true of nothing useful. You have to read every method to discover what it actually uses.
Failures move to runtime. A missing registration no longer fails at startup — it fails on the first request that reaches that line, possibly in production, possibly months later.
Testing gets worse. You cannot pass two fakes; you have to build a container, or mock
IServiceProvider and configure what it returns for each type.
The design smell is hidden. Eight dependencies no longer look like eight dependencies, so the pressure to split the class disappears.
⚠️ That last point is the real damage. Service locator does not just make one class worse — it removes the feedback that would have stopped the class growing.
How it works¶
The simple version — the three styles¶
// 2. [FromServices] — one action needs something the others do not
[HttpPost("export")]
public async Task<IActionResult> Export(
ExportRequest request,
[FromServices] IReportGenerator generator, // ← from DI, not the request body
CancellationToken ct)
{
var report = await generator.CreateAsync(request, ct);
return File(report, "application/pdf");
}
When [FromServices] earns its place¶
A controller with twelve actions where one needs an expensive service:
// Without [FromServices] — every action pays for it
public class OrdersController(
IOrderService orders,
IReportGenerator generator) : ControllerBase // only Export uses this
{
public IActionResult Get() { } // generator built anyway
public IActionResult List() { } // and here
public IActionResult Export() { } // only this one needs it
}
Constructor injection resolves every dependency when the controller is created, for every request — so a heavyweight service is built even for actions that never touch it.
[FromServices] defers it to the action that needs it.
⚠️ Do not over-apply this. Most services are cheap to construct, and scattering
[FromServices] across a controller makes the dependencies harder to see. It is a targeted
optimisation, not a style.
In .NET 7+ the attribute is often unnecessary for minimal APIs — the framework infers that a parameter whose type is registered in DI comes from services:
app.MapPost("/export", async (ExportRequest request, IReportGenerator generator) =>
{
// 'generator' resolved from DI automatically — no attribute needed
});
For controllers you can enable the same inference:
builder.Services.Configure<ApiBehaviorOptions>(o =>
o.DisableImplicitFromServicesParameters = false); // the default in .NET 7+
How it actually works — where the locator pattern is legitimate¶
Three cases where reaching into the container is correct:
1. A singleton needing scoped work — but use IServiceScopeFactory, not IServiceProvider
(6.5):
public class Worker(IServiceScopeFactory scopeFactory) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken ct)
{
using var scope = scopeFactory.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
}
}
2. Startup code in Program.cs — there is no constructor to inject into:
using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await db.Database.MigrateAsync();
3. Factory registrations — the lambda receives the provider by design (6.8).
4. Inline middleware — there is no constructor, so context.RequestServices is the only
option (5.4).
⚠️ The distinction: infrastructure code that composes the application may use the container. Application code that implements behaviour should not.
The deeper detail — the "too many parameters" argument¶
The most common defence of service locator is that a class has too many constructor parameters.
public class OrderService(
IOrderRepository repo,
IEmailSender email,
ISmsSender sms,
IPaymentGateway payments,
IInventoryService inventory,
IAuditLog audit,
IPricingEngine pricing,
ILogger<OrderService> logger) // eight and counting
{ }
Switching to IServiceProvider makes the list disappear from view. It does not make the class
simpler — it hides the complexity.
The real fixes:
Split the class. Eight dependencies usually means several responsibilities.
public class OrderService(
IOrderRepository repo,
IOrderNotifier notifier, // wraps email + SMS
IOrderPricing pricing, // wraps pricing + inventory
ILogger<OrderService> logger)
{ }
Group related dependencies behind a facade. Notification is one concern whether it goes by email or SMS.
Use IEnumerable<T> where the dependencies are variations of one thing
(6.7).
Question whether the class should exist. A service coordinating eight others is sometimes a sign the logic belongs in the domain model rather than a service layer (22.14).
Code¶
The same class, three ways, with the consequences visible.
// ✓ CONSTRUCTOR — dependencies visible, fails at startup, trivially testable
public class OrderService(
IOrderRepository repo,
IEmailSender email,
ILogger<OrderService> logger) : IOrderService
{
public async Task CompleteAsync(Guid id, CancellationToken ct)
{
var order = await repo.GetAsync(id, ct) ?? throw new NotFoundException(id);
order.Complete();
await repo.SaveAsync(order, ct);
await email.SendAsync(order.CustomerEmail, "Order complete", ct);
logger.LogInformation("Order {OrderId} completed", id);
}
}
// The test needs no container
var service = new OrderService(fakeRepo, fakeEmail, NullLogger<OrderService>.Instance);
// ✗ SERVICE LOCATOR — dependencies hidden, fails at runtime, awkward to test
public class OrderService(IServiceProvider provider) : IOrderService
{
public async Task CompleteAsync(Guid id, CancellationToken ct)
{
var repo = provider.GetRequiredService<IOrderRepository>();
var email = provider.GetRequiredService<IEmailSender>();
// ...
}
}
// The test has to build a container or mock the provider
var provider = Substitute.For<IServiceProvider>();
provider.GetService(typeof(IOrderRepository)).Returns(fakeRepo);
provider.GetService(typeof(IEmailSender)).Returns(fakeEmail);
// ...and repeat for every dependency the method happens to use
That test setup is the argument. It is longer, it breaks whenever the method resolves something new, and nothing tells you what to configure until the test fails.
Interview questions¶
Q: Why is constructor injection preferred?
Because the constructor becomes an honest, complete statement of what the class needs. That makes
dependencies visible to anyone reading it, lets a missing registration fail at object creation —
or at startup with ValidateOnBuild — and makes the class trivially testable by passing fakes
with no container involved. It also preserves a useful design signal: a constructor with eight
parameters obviously does too much, and that pressure pushes you to split the class.
Q: What is the service locator anti-pattern and why is it bad?
It is injecting IServiceProvider into a class and pulling services out on demand rather than
declaring them. It works, but it hides the dependencies — the constructor tells you the class
needs "the container", which is useless — so you have to read every method to find out what it
actually uses. It moves failures from startup to runtime, since a missing registration only
surfaces when that line executes. And it makes testing much worse, because you have to mock the
provider and configure what it returns per type. The subtlest damage is that it hides the design
smell, so nothing stops the class accumulating more dependencies.
Q: When is [FromServices] appropriate?
When one action on a controller needs a service the others do not, and that service is expensive
to construct. Constructor injection resolves every dependency for every request regardless of
which action runs, so a heavyweight report generator gets built even for a simple GET.
[FromServices] defers it to the action that uses it. I would use it sparingly though — most
services are cheap, and scattering the attribute makes the class's dependencies harder to see at
a glance. In .NET 7 and later the attribute is often unnecessary anyway, since parameters whose
types are registered in DI are inferred.
Q: A class has ten constructor parameters. Should you switch to IServiceProvider?
No — that hides the problem rather than solving it. Ten dependencies means the class has too many
responsibilities, and making the list invisible removes the only signal telling you so. The real
fixes are splitting the class, grouping related dependencies behind a facade — notification
covering both email and SMS, for instance — or using IEnumerable<T> where they are variations
of one thing. Occasionally it is a sign the logic belongs in the domain model rather than a
coordinating service.
Traps ⚠️¶
- Injecting
IServiceProviderinto application code hides dependencies and defers failures to runtime. - Using service locator to hide too many parameters removes the design feedback you needed.
[FromServices]everywhere makes dependencies hard to see. It is a targeted optimisation.- Constructor injection resolves everything per request, so a heavy service costs you even on actions that never use it.
- Injecting
IServiceProviderinto a singleton gives the root scope, which is a captive dependency waiting to happen (6.4). - Property injection is not supported by the built-in container. It requires a third-party one (6.11).
- Mocking
IServiceProviderin tests is brittle — it breaks whenever the method resolves something new.
Related¶
- 6.1 IoC and DI — why injection at all
- 6.2 The built-in container —
GetRequiredService - 6.5 Scopes — the legitimate use of
IServiceScopeFactory - 6.12 DI and testability — the testing argument in full
- 5.4 Inline middleware — where
RequestServicesis correct - 5.5 Conventional middleware — method injection
- 22.14 Anti-patterns — service locator in context