Covers the service locator anti-pattern: hidden dependencies, runtime failures, testability and lifetime bugs, and the legitimate infrastructure uses of IServiceProvider such as composition roots, factories, middleware and workers.
A service locator is when a class pulls its dependencies from a container (IServiceProvider.GetRequiredService<T>(), or a static ServiceLocator.Get<T>()) instead of declaring them in its constructor. It is harmful because it hides dependencies (the signature lies), moves missing-registration errors to run time on whatever code path hits them (and ValidateOnBuild can't see them), makes unit tests need a container, and invites lifetime bugs: resolving from the root in a singleton leaks transients or captures scoped services.
It is acceptable at the composition boundary: Program.cs, factory delegates (sp => ...), IServiceScopeFactory in a BackgroundService, framework-style code like middleware or a message dispatcher choosing a handler by type. The test: is this infrastructure wiring, or business logic asking for things?
"Service locator means a class asks for its dependencies at run time instead of declaring them. The textbook version is a static
ServiceLocator.Get<T>(); the modern version is injectingIServiceProviderand callingGetRequiredServiceinside methods. Both have the same problems. The constructor no longer tells you what the class needs, so you find out by reading every method. A missing registration doesn't fail at start-up; it fails on the one request that takes that branch, andValidateOnBuildcan't help because it only inspects constructors. Tests have to build or mock a container. And lifetimes get muddled: if thatIServiceProvideris the root, resolving a scoped service from a singleton either throws in Development or captures it in Production, and resolving disposable transients leaks them.That said, someone has to call the container.
Program.csdoes. Factory registrations do:sp => new Foo(sp.GetRequiredService<IBar>())is the container's own API. ABackgroundServicecreating a scope per message and resolving one handler is fine, because that's infrastructure creating units of work. A mediator or message dispatcher that resolvesIHandler<TMessage>by type is fine for the same reason. The test I apply is: is this code wiring things up, or is it business logic that just didn't want to declare a dependency?The mistake I see is people injecting
IServiceProviderto dodge a big constructor or a circular dependency. That hides the design problem rather than fixing it. If you need run-time selection, there's usually a typed option:IEnumerable<T>, keyed services, or a small factory interface."
| Problem | Effect |
|---|---|
| Hidden dependencies | Constructor lies; reviewers and tooling can't see the graph |
| Run-time failures | InvalidOperationException: No service for type 'X' in production on a rare path |
| Validation blind spot | ValidateOnBuild checks constructors, not method bodies |
| Testing | Tests need a real container or a mocked IServiceProvider |
| Lifetime bugs | Root resolution leaks transient disposables or captures scoped services |
| Code | Acceptable? | Why |
|---|---|---|
Program.cs, AddXxx() extension methods |
Yes | Composition root |
Factory delegate sp => ... in a registration |
Yes | Part of composition |
BackgroundService using IServiceScopeFactory per message |
Yes | Infrastructure creating units of work |
Dispatcher resolving IHandler<T> by message type |
Yes (keep it small) | Framework-style code |
Middleware InvokeAsync parameters |
Yes | Framework does the resolution |
Domain service calling GetService in a method |
No | Hidden dependency |
Static ServiceLocator.Current |
No | Global state, untestable |
| Need | Use |
|---|---|
| Choose one of several implementations | IEnumerable<T> + a selector, or keyed services ([FromKeyedServices]) |
| Create instances on demand | Func<T>, a typed factory interface, IDbContextFactory<T> |
| Expensive and rarely used | Lazy<T> registration (sparingly) or a factory |
| Break a cycle | Redesign; extract the shared part into a third service |
A payments service injected IServiceProvider into [14] classes. A refactor removed the registration for IRefundGateway; build and tests passed, and the first refund in production [three days later] failed with 'No service for type IRefundGateway'. Moving those dependencies into constructors meant ValidateOnBuild caught the next removed registration at start-up in CI.
Checks that the candidate can explain why the service locator hurts and can tell legitimate infrastructure use of IServiceProvider from hidden dependencies.
Green flags
ValidateOnBuild blind spotIServiceProvider in a singleton is the root providerIEnumerable<T>, factoriesRed flags
IServiceProvider everywhere for convenienceStatic locator Injected locator
-------------- ----------------
class OrderService class OrderService(IServiceProvider sp)
{ {
void Place() { void Place() {
var repo = ServiceLocator var repo = sp.GetRequiredService<IRepo>();
.Get<IRepo>(); }
} }
}
The injected form looks like DI, but the class still depends on the container rather than on IRepo.
ValidateOnBuild builds a call site for every registered service by inspecting its constructor. A GetRequiredService<IRefundGateway>() call inside a method body is invisible, so a missing registration is a latent run-time error.
The IServiceProvider you receive by injection is the provider of the scope that resolved you:
That difference is why the same locator code behaves differently depending on its own lifetime.
ActivatorUtilities.CreateInstance (controllers, middleware).InvokeAsync(HttpContext, IScopedDep) parameters resolved from HttpContext.RequestServices per request.These are composition infrastructure, written once and tested heavily, which is why they're acceptable.
IEnumerable<T>, keyed services or a factory interface.ValidateOnBuild and fix what it finds.ValidateOnBuild still passes and the call fails at run time.IServiceProvider into a singleton and a scoped service; resolve a scoped dependency from each and compare behaviour with ValidateScopes on.IServiceProvider usage outside a composition namespace.Before: an injected service locator. After: explicit dependencies plus a keyed selection.
namespace Payments;
public interface IRefundGateway { Task RefundAsync(Guid paymentId, decimal amount, CancellationToken ct); }
public interface IPaymentRepository { Task<Payment> GetAsync(Guid id, CancellationToken ct); }
public sealed record Payment(Guid Id, string Provider, decimal Amount);
// BEFORE: what does this class need? You have to read every line to find out.
public sealed class RefundServiceLocator(IServiceProvider services)
{
public async Task RefundAsync(Guid paymentId, CancellationToken ct)
{
var repo = services.GetRequiredService<IPaymentRepository>();
var payment = await repo.GetAsync(paymentId, ct);
// Fails at run time, on this path only, if the provider isn't registered.
var gateway = services.GetRequiredKeyedService<IRefundGateway>(payment.Provider);
await gateway.RefundAsync(payment.Id, payment.Amount, ct);
}
}
// AFTER: the constructor states the dependencies; selection is a typed, testable concept.
public interface IRefundGatewaySelector { IRefundGateway For(string provider); }
public sealed class RefundService(IPaymentRepository payments, IRefundGatewaySelector gateways)
{
public async Task RefundAsync(Guid paymentId, CancellationToken ct)
{
var payment = await payments.GetAsync(paymentId, ct);
await gateways.For(payment.Provider).RefundAsync(payment.Id, payment.Amount, ct);
}
}
// The one place that touches the container is infrastructure, next to the registrations.
internal sealed class KeyedRefundGatewaySelector(IServiceProvider services) : IRefundGatewaySelector
{
public IRefundGateway For(string provider) =>
services.GetKeyedService<IRefundGateway>(provider)
?? throw new InvalidOperationException($"No refund gateway for provider '{provider}'.");
}
// Program.cs
builder.Services.AddKeyedScoped<Payments.IRefundGateway, StripeRefundGateway>("stripe");
builder.Services.AddKeyedScoped<Payments.IRefundGateway, AdyenRefundGateway>("adyen");
builder.Services.AddScoped<Payments.IRefundGatewaySelector, Payments.KeyedRefundGatewaySelector>();
builder.Services.AddScoped<Payments.RefundService>();
A unit test now needs no container:
namespace Payments.Tests;
public sealed class RefundServiceTests
{
[Fact]
public async Task Refunds_through_the_payment_provider()
{
var gateway = new FakeGateway();
var sut = new RefundService(new FakeRepo(new Payment(Guid.NewGuid(), "stripe", 50m)), new FixedSelector(gateway));
await sut.RefundAsync(Guid.NewGuid(), CancellationToken.None);
Assert.Equal(50m, gateway.Refunded);
}
private sealed class FakeGateway : IRefundGateway
{
public decimal Refunded { get; private set; }
public Task RefundAsync(Guid id, decimal amount, CancellationToken ct) { Refunded = amount; return Task.CompletedTask; }
}
private sealed class FakeRepo(Payment p) : IPaymentRepository { public Task<Payment> GetAsync(Guid id, CancellationToken ct) => Task.FromResult(p); }
private sealed class FixedSelector(IRefundGateway g) : IRefundGatewaySelector { public IRefundGateway For(string provider) => g; }
}
IServiceProvider to avoid a long constructor. Why it is wrong: The dependencies are still there, just hidden; the class still violates SRP. Instead: Split the class or introduce a facade service.GetService<T>() (nullable) and assuming it's non-null. Why it is wrong: Missing registrations become NullReferenceExceptions far from the cause. Instead: If you must resolve, use GetRequiredService<T>() so the error names the type.IServiceProvider injected into a singleton. Why it is wrong: That is the root provider; you get a captive or leaked instance. Instead: Create a scope with IServiceScopeFactory.IServiceProvider everywhere, including factories and workers. Why it is wrong: Composition code legitimately needs it; contortions to avoid it add complexity. Instead: Confine it to composition and infrastructure namespaces.IServiceProvider in unit tests. Why it is wrong: Tests couple to implementation details and break on every refactor. Instead: Inject the real dependencies and pass fakes.I don't treat IServiceProvider as forbidden; I treat it as infrastructure-only. The question is where the call sits. A dispatcher, a factory or a worker resolving one entry point per unit of work is composition code; it is small, tested and changes rarely. A domain service resolving things in method bodies is hiding its design. I enforce the boundary with an analyser rule rather than code review alone, because the pattern creeps back in under deadline pressure.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Constructor injection | Default | Visible, sometimes long constructors | Never a wrong default |
Keyed services / IEnumerable<T> |
Select implementation by key at run time | .NET 8+ for keyed; key strings need care | Selection is fixed at start-up |
| Typed factory interface | Create instances on demand, run-time args | One small extra type | When a scoped dependency would do |
IServiceScopeFactory |
Workers, dispatchers creating units of work | Locator-like inside infrastructure | Business logic |
IServiceProvider in domain code |
Almost never | Hidden deps, late failures | Default |
I measure the benefit by how often missing registrations reach production (should be zero once ValidateOnBuild sees every dependency) and by how many tests need a container.
The composition root is the single place where the application's object graph is wired up: in ASP.NET Core, Program.cs and the AddXxx() extension methods it calls. It is the only code that knows about concrete implementations and the container.
Everything else asks for what it needs through its constructor. If business classes call IServiceProvider.GetService themselves, that is the service locator anti-pattern: their dependencies are hidden from the signature, a missing registration only shows up at run time, and unit tests need a container instead of a couple of fakes. Keeping resolution in the root keeps business code independent of the container, easier to test and easier to maintain. Framework-driven resolution (middleware Invoke parameters, [FromServices], Minimal API parameters) is fine because it is infrastructure acting on your behalf.
I'd use a strangler approach, not a rewrite. First, characterisation tests around the code I'll touch first. Then a single composition root (the Generic Host in modern .NET, or ServiceCollection built in the old entry point) and a bridge: the legacy ServiceLocator.Get<T>() delegates to the real IServiceProvider, so old and new code share the same instances.
From there I convert from the edges inwards: new code and any class I touch takes constructor dependencies; statics get thin adapters behind interfaces. I track locator call count as a metric and block new usages with an analyser.
The trade-off: for months the codebase is half old, half new, which is uglier than a rewrite plan but keeps shipping.
The 12-parameter constructor is a symptom: the class has several responsibilities (placing, cancelling, notifying, invoicing, auditing). The new calls are the bugs.
new HttpClient() in a method: socket exhaustion under load and stale DNS. Use IHttpClientFactory or a typed client.new TaxCalculator(): a hidden dependency that can't be faked or configured. Inject it.The trade-off: more, smaller classes, in exchange for code where each class can be understood and tested on its own.
Last updated 23 Nov 2026.