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

📚 Interview question

What do ValidateScopes and ValidateOnBuild check in the .NET service provider? Explain the exact errors each one raises, why the host turns them on only in Development by default, whether you should turn them on everywhere, and what kinds of DI mistakes they still can't catch.

ServiceProviderOptions.ValidateScopes and ValidateOnBuild: what each validates and when (resolution versus build), the error messages, the Development-only default in the Generic Host, enabling them in tests or production with UseDefaultServiceProvider, their cost and their blind spots (factories, open generics, service locator calls, root-resolved transients).

Mid-Level Theory Intermediate aspnet-core dependency-injection service-lifetimes validate-on-build validate-scopes

🎯 Key points

  • ValidateScopes throws InvalidOperationException naming the types: "Cannot consume scoped service 'X' from singleton 'Y'" and "Cannot resolve scoped service 'X' from root provider"
  • ValidateScopes is checked when a call site is first resolved (or at build if ValidateOnBuild is on), including transitive singleton -> transient -> scoped chains
  • ValidateOnBuild builds a call site (without constructing the service) for every non-open-generic descriptor at Build(); each failure is an InvalidOperationException, collected into one AggregateException 'Some services are not able to be constructed'
  • The Generic Host defaults both to IsDevelopment(); override in any environment with builder.Host.UseDefaultServiceProvider
  • Cost: a one-off start-up walk for ValidateOnBuild (tens to hundreds of ms) and a small first-resolution check for ValidateScopes
  • Blind spots: dependencies resolved inside factory delegates, open generics, IServiceProvider calls in code, transient disposables captured by the root, valid-but-wrong wiring
  • Best practice: always on in an integration test that builds the production composition root; on in production when start-up probes and automatic rollback exist

⏱ 30-second answer

Both are ServiceProviderOptions. ValidateScopes stops lifetime mistakes: it throws "Cannot consume scoped service from singleton" (a captive dependency) and "Cannot resolve scoped service from root provider", checked when a service's call site is first resolved. ValidateOnBuild tries to build a call site for every non-open-generic registration when the provider is built, so missing registrations and cycles fail at start-up with an AggregateException. The Generic Host turns both on only in Development to keep production start-up lean and avoid breaking apps that had latent issues. I turn them on in an integration test that builds the real composition root, so every PR is checked. Their limit: they can't see inside factory delegates, open generics or IServiceProvider calls in your code.

🗣 Full answer (senior)

How I would answer this in an interview

"They catch different classes of mistakes at different times. ValidateScopes is about lifetimes. When a call site is resolved, the provider checks whether a singleton depends, directly or transitively, on something scoped, and throws Cannot consume scoped service 'AppDbContext' from singleton 'PricingCache'. It also throws if you resolve a scoped service straight from the root provider, which is what happens when someone calls app.Services.GetRequiredService<AppDbContext>() at start-up. Without it, both mistakes silently create a captive instance that lives forever.

ValidateOnBuild is about completeness. At Build() the provider walks every descriptor that isn't an open generic and builds its call site. Missing registrations, unresolvable constructors and circular dependencies are collected into one AggregateException listing each failing service. Combined with ValidateScopes, captive dependencies also fail at start-up instead of on first use.

WebApplication.CreateBuilder sets both to IsDevelopment(). The reasoning is start-up cost and compatibility: big apps can have thousands of registrations, and turning validation on in production for an existing app could stop it booting over a service nobody uses. The mistake I see is relying on that default: a service only used by one endpoint that developers never hit locally isn't validated until it fails in production. So I always have an integration test that builds the real host with both options on, and on newer services I turn them on in production too, because a failed start-up is caught by the deployment's health check, while a captive DbContext corrupts data quietly. I also know their limits: dependencies inside a factory lambda, open generics and anything resolved through IServiceProvider in code aren't checked."


What each one checks

ValidateScopes ValidateOnBuild
Catches Scoped in singleton (captive); scoped resolved from root Missing registrations, no usable constructor, cycles (and captive, with ValidateScopes)
When First resolution of each call site BuildServiceProvider() / builder.Build()
Error InvalidOperationException per resolution AggregateException: "Some services are not able to be constructed"
Cost A small check on first resolution; root scope tracking One walk of all descriptors at start-up
Default IsDevelopment() IsDevelopment()

What they can't catch

Blind spot Why Mitigation
Factory delegates sp => new X(sp.GetRequiredService<Y>()) The lambda is opaque until it runs Prefer type registrations; test-resolve factory services
Open generics No type argument at build time Resolve the closed types you use in a test
IServiceProvider.GetService in code Not part of the graph Avoid the service locator; integration-test the path
Transient disposables resolved from root Legal, just leaks dotnet-gcdump; code review
Wrong but valid wiring (wrong implementation) Container can't know intent Assert resolved types in tests

Production example

On an [ordering platform] with about 900 registrations, enabling ValidateOnBuild in production added about 120 ms to start-up and found three broken services that only background jobs used. We kept it on: a pod that fails its start-up probe is rolled back automatically, which beats a background job failing silently at 2 am.

🔍 What the interviewer is checking

Checks whether the candidate knows precisely what the two validation options catch, when they run, their Development-only default and their blind spots.

Green flags

  • Gives the two ValidateScopes errors and the build-time AggregateException
  • Knows the IsDevelopment() default and how to override it
  • Names blind spots: factories, open generics, service locator calls
  • Proposes a composition-root integration test in the production environment

Red flags

  • Thinks validation runs in production by default
  • Believes ValidateOnBuild instantiates every service
  • Can't explain the difference between the two

📚 Learn in depth

1. Where the options come from

new ServiceProviderOptions { ValidateScopes = ..., ValidateOnBuild = ... }

HostApplicationBuilder (behind WebApplication.CreateBuilder) configures the default provider factory with ValidateScopes = ValidateOnBuild = environment.IsDevelopment(). You override with builder.Host.UseDefaultServiceProvider((ctx, o) => { ... }) or builder.ConfigureContainer(new DefaultServiceProviderFactory(options)).

2. ValidateScopes internals

When enabled, the provider creates a CallSiteValidator. For each call site it computes whether the graph contains a scoped service and remembers it:

Resolve(PricingCache)  [singleton]
  CallSiteValidator.Validate
    walks: PricingCache -> PriceRepository -> AppDbContext [scoped]
    -> throw "Cannot consume scoped service 'AppDbContext' from singleton 'PricingCache'."

Root.GetService(AppDbContext) [scoped]
    -> throw "Cannot resolve scoped service 'AppDbContext' from root provider."

A transitive case (singleton → transient → scoped) is also caught because the validator walks the whole call site tree.

3. ValidateOnBuild internals

At construction, the provider loops over descriptors (skipping open generic ones), calls GetCallSite for each and, if ValidateScopes is on, runs the scope validator. Exceptions are collected and thrown together:

AggregateException: Some services are not able to be constructed
  (Error while validating the service descriptor 'ServiceType: IEmailSender Lifetime: Scoped
   ImplementationType: SmtpEmailSender': Unable to resolve service for type 'ISmtpClient'...)
  (Error while validating ... A circular dependency was detected ...)

It builds call sites but does not construct the services, so constructors with side effects don't run.

4. Why factories are blind spots

AddScoped<IX>(sp => new X(sp.GetRequiredService<IY>())) is a FactoryCallSite. The validator sees "a factory that returns IX" and can't know it will ask for IY. If IY is missing or scoped-in-singleton, you only learn at the first call. That's another reason to prefer type registrations or ActivatorUtilities.CreateInstance inside factories with a test that resolves the service.

5. Turning them on everywhere

Trade-offs: start-up time (usually tens to hundreds of milliseconds), and the risk that an existing app has unused broken registrations that now stop it booting. In containers with start-up probes and automatic rollback, failing fast is usually the better outcome. At minimum, run them in an integration test using WebApplicationFactory<Program> with the production environment name.

Try it yourself

  1. Register a singleton that depends on a scoped service, set the environment to Production and observe no error; switch to Development and read the exception.
  2. Register a service with a missing dependency and compare the error with and without ValidateOnBuild.
  3. Move the missing dependency inside a factory lambda and confirm ValidateOnBuild no longer reports it.
  4. Write a WebApplicationFactory test with UseEnvironment("Production") and UseDefaultServiceProvider forcing both options on.
  5. Measure start-up with and without ValidateOnBuild using dotnet-counters or a Stopwatch around builder.Build().

💻 Code

Turning validation on everywhere, and a test that validates the production composition root (.NET 10, xUnit, Microsoft.AspNetCore.Mvc.Testing):

var builder = WebApplication.CreateBuilder(args);

// Default is IsDevelopment(); force both on in every environment.
builder.Host.UseDefaultServiceProvider(options =>
{
    options.ValidateScopes = true;
    options.ValidateOnBuild = true;
});

builder.Services.AddDbContext<AppDbContext>(); // scoped
builder.Services.AddSingleton<PricingCache>();  // BUG: depends on AppDbContext
// With ValidateScopes + ValidateOnBuild, Build() throws:
// Cannot consume scoped service 'AppDbContext' from singleton 'PricingCache'.

var app = builder.Build();
app.Run();

public sealed class PricingCache(AppDbContext db);
public partial class Program;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Ordering.Tests;

public sealed class CompositionRootTests
{
    [Fact]
    public void Production_composition_root_is_valid()
    {
        using var factory = new WebApplicationFactory<Program>().WithWebHostBuilder(b =>
        {
            b.UseEnvironment(Environments.Production); // validate the real wiring, not Development's
            b.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; });
        });

        // Building the host runs ValidateOnBuild; failures surface as AggregateException.
        using var scope = factory.Services.CreateScope();

        // Cover a blind spot: services registered with factory delegates.
        Assert.NotNull(scope.ServiceProvider.GetRequiredService<IReportExporterFactory>());
    }
}

⚠ Common mistakes

  • Mistake: Assuming captive dependencies are caught in production because they were caught locally once. Why it is wrong: both options default to Development only. Instead: force them on in an integration test (and ideally in production).
  • Mistake: Thinking ValidateOnBuild constructs every service. Why it is wrong: it only builds call sites; constructor logic doesn't run. Instead: test behaviour separately; use validation for wiring.
  • Mistake: Believing ValidateOnBuild covers factory registrations. Why it is wrong: dependencies resolved inside the lambda are invisible. Instead: prefer type registrations and test-resolve factory services.
  • Mistake: Relying on validation for open generics. Why it is wrong: open descriptors are skipped. Instead: resolve each closed type you use in a test.
  • Mistake: Resolving scoped services from app.Services at start-up (for migrations or seeding). Why it is wrong: it resolves from the root, which ValidateScopes rejects and which leaks without it. Instead: using var scope = app.Services.CreateScope(); and resolve from the scope.
  • Mistake: Running the composition-root test in the Development environment. Why it is wrong: production-only registrations (Key Vault, real senders) aren't exercised. Instead: use UseEnvironment("Production") with test-safe configuration.

🏛 Senior insight: trade-offs

These two flags are the cheapest DI safety net available, and the Development-only default means most teams get none of that protection where it matters. My stance: always on in an integration test that builds the production composition root; on in production for new services where a start-up probe and automatic rollback exist; for a large legacy app, turn them on in tests first, fix what they find, then enable in production.

Option When it fits Cost When not to
Default (Development only) Never sufficient on its own None Any app with production-only wiring
On in integration tests Every app Milliseconds per test run Never skip
On in production Containers with probes and rollback 10s–100s of ms start-up Legacy apps with known broken registrations not yet fixed
Third-party analysers / resolve-all tests Covering factories and open generics Test code to maintain Small apps where validation covers everything

Measure start-up impact with a timer around builder.Build() in each environment; for most services it's well under the probe budget.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions captive dependencies Why: Checks the definition of a captive dependency and how ValidateScopes catches it
    How to answer

    A captive dependency is a shorter-lived service captured by a longer-lived one, usually a scoped DbContext held by a singleton. The scoped instance stops being per-request: in production it is shared across threads (EF's "second operation" exceptions), serves stale data from its identity map, keeps growing its change tracker and is never disposed.

    ValidateScopes = true makes the provider throw when a singleton's graph contains a scoped service or a scoped service is resolved from the root. The host enables it only in Development by default; turn it on everywhere with builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; }). The cost is a small check on resolution and a one-off graph walk at start-up, far cheaper than the outage. Fix by aligning lifetimes, or creating per-operation instances with IDbContextFactory<T> or IServiceScopeFactory.

  2. When: Candidate describes stale or cross-user data from a singleton Why: Checks diagnosing and fixing a captive dependency in production
    How to answer

    A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.

    ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.

    The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.

  3. When: Candidate explains ValidateOnBuild Why: Checks the limits of ValidateOnBuild in more depth
    How to answer

    ValidateOnBuild makes Build() walk every registration and try to build its call site, so a missing dependency or an unresolvable constructor fails at start-up instead of on the first request that needs it. Combined with ValidateScopes it also catches a singleton depending on a scoped service.

    What it cannot catch:

    • anything inside a factory delegate (sp => ...): the body is opaque code that only runs on resolution;
    • open generics, which can't be checked until a closed type is requested;
    • types created later with ActivatorUtilities.CreateInstance or GetService calls in your own code.

    ASP.NET Core's WebApplication turns it on only in the Development environment; enable it everywhere with builder.Host.UseDefaultServiceProvider(o => { o.ValidateOnBuild = true; o.ValidateScopes = true; }). The start-up cost is a one-off graph walk, typically small, and it buys you a fast failure in every environment.

🛠 Real-world problems: how you handle them

Captive DbContext reached production because validation was Development-only
Situation
A [customer-portal] API on .NET [10] in Azure App Service [Australia Southeast]. A new singleton `LoyaltyCache` took the scoped `PortalDbContext`. It was only resolved by a background refresh job that never ran in local Development sessions, so the Development-only `ValidateScopes` never saw it.
Signals
Intermittent `InvalidOperationException: A second operation was started on this context instance` from the refresh job, and loyalty balances that stopped updating after the first refresh. Customers reported stale points in [support tickets].
Investigation
Exception stack traces pointed at `LoyaltyCache`. Building the host locally with `UseEnvironment("Production")` and `UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; })` threw `Cannot consume scoped service 'PortalDbContext' from singleton 'LoyaltyCache'` at start-up.
Resolution
Hotfix: changed `LoyaltyCache` to use `IServiceScopeFactory.CreateAsyncScope()` per refresh and keep only plain data in the singleton. Then turned on both validation options in production with the App Service health check as a safety net.
Prevention
A composition-root integration test in the Production environment on every PR; validation forced on in all environments; a review checklist item for singletons with database dependencies.

How to tell it (STAR)

**S:** On [our customer portal], loyalty balances stopped updating and the refresh job threw EF Core concurrency errors. **T:** I had to fix the data issue and work out why our checks hadn't caught it. **A:** The stack traces pointed at a new singleton cache that took the scoped `DbContext`. Scope validation only ran in Development, and the job never ran locally. I fixed the cache to create a scope per refresh, then added an integration test that builds the production host with both validation flags on, and enabled them in production behind the health check. **R:** Balances were correct again after [one] refresh cycle, start-up grew by only [about 80 ms], and the test has blocked [two] more captive dependencies since.

More in Advanced DI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me