📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the service locator anti-pattern? Why is injecting IServiceProvider and calling GetRequiredService inside your classes considered harmful, and where in an ASP.NET Core app is resolving from IServiceProvider acceptable?

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.

Intermediate Theory Intermediate anti-patterns aspnet-core dependency-injection iserviceprovider service-locator testability

🎯 Key points

  • Service locator: a class asks a global or injected container for its dependencies instead of declaring them
  • Hides dependencies from the constructor signature, so the API lies about what the class needs and the graph is hard to follow
  • Missing registrations fail at run time on that code path; ValidateOnBuild only inspects constructors, not method bodies
  • Unit tests need a container or a mocked IServiceProvider
  • Lifetime bugs: resolving from the root provider in singletons leaks transient disposables or captures scoped services
  • Acceptable at the composition boundary: Program.cs, factory delegates, IServiceScopeFactory in workers, middleware/framework code, plugin dispatch
  • Over time it becomes technical debt: changes ripple unpredictably because nobody can see who depends on what
  • Prefer constructor injection, Func<T>/typed factories, keyed services or IEnumerable<T> for run-time selection

⏱ 30-second answer

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?

🗣 Full answer (senior)

How I would answer this in an interview

"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 injecting IServiceProvider and calling GetRequiredService inside 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, and ValidateOnBuild can't help because it only inspects constructors. Tests have to build or mock a container. And lifetimes get muddled: if that IServiceProvider is 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.cs does. Factory registrations do: sp => new Foo(sp.GetRequiredService<IBar>()) is the container's own API. A BackgroundService creating a scope per message and resolving one handler is fine, because that's infrastructure creating units of work. A mediator or message dispatcher that resolves IHandler<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 IServiceProvider to 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."


Why it hurts

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

Acceptable vs not

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

Better alternatives for run-time selection

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate can explain why the service locator hurts and can tell legitimate infrastructure use of IServiceProvider from hidden dependencies.

Green flags

  • Names hidden dependencies, run-time failures and the ValidateOnBuild blind spot
  • Knows an injected IServiceProvider in a singleton is the root provider
  • Lists legitimate uses: composition root, factory delegates, workers, dispatchers
  • Offers typed alternatives: keyed services, IEnumerable<T>, factories

Red flags

  • Uses IServiceProvider everywhere for convenience
  • Thinks it's fine because it's injected rather than static
  • Cannot name any legitimate use

📚 Learn in depth

1. Two forms of the pattern

Static 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.

2. What validation can and can't see

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.

3. Which provider are you holding?

The IServiceProvider you receive by injection is the provider of the scope that resolved you:

  • In a scoped or transient service resolved in a request: the request scope. Scoped resolution works.
  • In a singleton: the root provider. Scoped services throw (Development) or become effectively singletons; transient disposables are tracked until shutdown.

That difference is why the same locator code behaves differently depending on its own lifetime.

4. Where the framework itself uses it

  • ActivatorUtilities.CreateInstance (controllers, middleware).
  • Middleware InvokeAsync(HttpContext, IScopedDep) parameters resolved from HttpContext.RequestServices per request.
  • Minimal API parameter binding of services.
  • MediatR / message buses resolving handlers.

These are composition infrastructure, written once and tested heavily, which is why they're acceptable.

5. Refactoring away from a locator

  1. List every type the class resolves.
  2. Move each to the constructor.
  3. If the list is long, that's an SRP problem; split the class.
  4. If selection is dynamic, introduce IEnumerable<T>, keyed services or a factory interface.
  5. Turn on ValidateOnBuild and fix what it finds.

Try it yourself

  1. Write a class that resolves a service in a method; remove the registration; confirm ValidateOnBuild still passes and the call fails at run time.
  2. Move it to the constructor and confirm start-up now fails.
  3. Inject IServiceProvider into a singleton and a scoped service; resolve a scoped dependency from each and compare behaviour with ValidateScopes on.
  4. Use a BannedApiAnalyzers rule to flag IServiceProvider usage outside a composition namespace.

💻 Code

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; }
}

⚠ Common mistakes

  • Mistake: Injecting 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.
  • Mistake: Using a locator to break a circular dependency. Why it is wrong: The cycle still exists at run time and now fails late or recursively. Instead: Redesign: extract the shared logic into a third service or use events.
  • Mistake: Calling 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.
  • Mistake: Resolving scoped services from an 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.
  • Mistake: Banning 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.
  • Mistake: Mocking 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the composition root Why: Checks they can define where resolution belongs
    How to answer

    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.

  2. When: Candidate mentions a legacy static ServiceLocator Why: Checks an incremental strategy for removing one
    How to answer

    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.

  3. When: Candidate says IServiceProvider is used to avoid long constructors Why: Checks they treat constructor over-injection as a design smell
    How to answer

    The 12-parameter constructor is a symptom: the class has several responsibilities (placing, cancelling, notifying, invoicing, auditing). The new calls are the bugs.

    1. new HttpClient() in a method: socket exhaustion under load and stale DNS. Use IHttpClientFactory or a typed client.
    2. new TaxCalculator(): a hidden dependency that can't be faked or configured. Inject it.
    3. Over-injection: split by use case into focused handlers with 3-4 dependencies each, move side effects (email, SMS, PDF, audit) into domain event handlers, and introduce a facade only for a genuinely cohesive group like notifications.

    The trade-off: more, smaller classes, in exchange for code where each class can be understood and tested on its own.

↩ Usually asked after

More in Service Lifetimes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me