skip to content

In ASP.NET Core 10, what do ServiceProviderOptions.ValidateScopes and ValidateOnBuild each check, and why might a captive dependency still reach production?

level: middleimportance: should knowfreq 46%

answer

  1. both default to false
  2. on only when IsDevelopment()
  3. resolution-time vs build-time check
  4. AggregateException from builder.Build()
  5. factory lambdas are not walked

basics

~10 s

ValidateScopes rejects scoped services resolved from the root provider or captured by singletons; ValidateOnBuild checks every registration at builder.Build(). WebApplicationBuilder enables both only in Development, and factory lambdas escape the build-time check.

solid answer

~40 s

`ValidateScopes` makes the provider throw `InvalidOperationException` when a scoped service is resolved from the root provider ("Cannot resolve scoped service 'X' from root provider.") or sits in a singleton's constructor graph ("Cannot consume scoped service 'X' from singleton 'Y'."). `ValidateOnBuild` builds the plan for every registration when the provider is created and throws one `AggregateException`, "Some services are not able to be constructed", listing each failure. Both default to `false`; `WebApplicationBuilder` sets both to `true` only when the environment is Development, and since .NET 9 the plain `HostBuilder` does the same. A captive still ships because Staging and Production run without them, factory lambdas such as `AddSingleton(sp => ...)` are opaque to the build-time walk, open generics are skipped, and a replaced container ignores these options. `builder.Host.UseDefaultServiceProvider` turns them on anywhere.

code

csharp · 10 lines
csharp
var builder = WebApplication.CreateBuilder(args);

// Development already does this; apply it in every environment:
builder.Host.UseDefaultServiceProvider(o =>
{
    o.ValidateScopes = true;   // scoped-from-root and scoped-in-singleton
    o.ValidateOnBuild = true;  // walk every registration at Build()
});

var app = builder.Build(); // AggregateException here if any registration fails

go deeper

for a junior

Recall that ASP.NET Core checks DI lifetimes at startup in Development and that the error mentions consuming a scoped service from a singleton.

for a middle

Explain the split: ValidateScopes at resolution, ValidateOnBuild at builder.Build(), both false by default and turned on by WebApplicationBuilder only in Development.

for a senior

Name the blind spots, factory lambdas, open generics, service location and replaced containers, and decide whether to enable the checks beyond Development.

for a principal

Treat lifetime validation as a guardrail: decide which environments and pipelines must build the host with validation on so production never meets an unchecked graph.

## Two options on the default provider The built-in container is configured through `ServiceProviderOptions` (namespace `Microsoft.Extensions.DependencyInjection`). It has two Boolean properties, both `false` unless something sets them: | Option | When it runs | What it rejects | How it fails | |---|---|---|---| | `ValidateScopes` | on every resolution, plus during the build-time walk | a scoped service resolved from the **root** provider; a scoped service anywhere in a **singleton's** constructor graph | `InvalidOperationException` | | `ValidateOnBuild` | once, when the provider is built (`builder.Build()`) | any registration whose constructor graph cannot be built: missing dependency, no usable constructor, captive scoped service | one `AggregateException` collecting every failure | The messages are worth recognising on sight: - "Cannot consume scoped service 'TradingDbContext' from singleton 'IQuoteCache'." (a scoped service inside a singleton's graph) - "Cannot resolve scoped service 'TradingDbContext' from root provider." (asking `app.Services` for a scoped service directly) - "Cannot resolve 'IOrderReport' from root provider because it requires scoped service 'TradingDbContext'." (asking the root for a transient that needs a scoped one) - "Some services are not able to be constructed" with inner "Error while validating the service descriptor ..." entries (the build-time aggregate) The build-time walk reports captives only because it reuses the scope validator, so `ValidateOnBuild` finds lifetime mismatches only when `ValidateScopes` is also on. In Development both are. ## Who turns them on - `WebApplicationBuilder` (what `WebApplication.CreateBuilder(args)` returns) creates its default provider factory with `ValidateScopes = true` and `ValidateOnBuild = true` **only when `IHostEnvironment.IsDevelopment()` is true**; otherwise it uses plain defaults. - `Host.CreateDefaultBuilder` sets both to the result of `IsDevelopment()` as well. - Since **.NET 9**, a bare `new HostBuilder()` also enables both in Development when you have not configured the provider yourself. Before that, only the default builders did. So a stock-trading dashboard run locally with `ASPNETCORE_ENVIRONMENT=Development` fails fast, while the same build deployed to Staging or Production starts without complaint. ## Why a captive still reaches production 1. **Environment.** Nobody runs the app in Development in CI, or a worker or test host starts in Production mode. No validation, no failure. 2. **Factory registrations are opaque.** The validator cannot look inside a lambda. With ```csharp builder.Services.AddSingleton<IQuoteCache>(sp => new QuoteCache(sp.GetRequiredService<TradingDbContext>())); ``` `ValidateOnBuild` passes. The capture surfaces only when the singleton is first resolved: the lambda receives the root provider, so with `ValidateScopes` on it throws "Cannot resolve scoped service 'TradingDbContext' from root provider." With validation off it silently captures a root-held context. 3. **Open generic registrations are skipped** by `ValidateOnBuild`; their closed forms are checked only when resolved. 4. **Service location.** Code that calls `GetRequiredService` at run time is checked only when that path runs, so a rarely hit branch can hide a mismatch. 5. **A replaced container.** These are options of the default provider; a third-party container plugged in through `UseServiceProviderFactory` applies its own rules instead. ## Reading the failure When `builder.Build()` throws in Development, read the aggregate before changing anything: - Every inner exception starts with "Error while validating the service descriptor" and prints the descriptor: its service type, lifetime and implementation type. That tells you **which registration** is wrong. - The rest of the message tells you **why**: a missing registration ("Unable to resolve service for type ..."), or a lifetime mismatch ("Cannot consume scoped service ..."). - Type names are printed with their namespaces, so the offending pair is unambiguous even in a solution with several `TradingDbContext`-like names. - Fix the **ownership** the message points at (the singleton must stop holding the scoped service) rather than loosening the check or flipping the dependency to singleton. ## Turning validation on everywhere `builder.Host` accepts the generic-host extension: ```csharp var builder = WebApplication.CreateBuilder(args); builder.Host.UseDefaultServiceProvider(o => { o.ValidateScopes = true; o.ValidateOnBuild = true; }); ``` Trade-offs to state: - `ValidateOnBuild` costs startup time proportional to the number of registrations, paid once. - `ValidateScopes` adds a check to resolutions; small, but not free on a hot path. - A middle ground is to keep them on in every non-production environment and to have a test build the host in Development, so a production build never ships an unchecked graph. ## The interview answer in one breath `ValidateScopes` guards lifetimes at resolution, `ValidateOnBuild` guards the whole graph at startup, both are Development-only by default, and lambdas, open generics, service location and other containers are the blind spots.

  • Why does AddSingleton(sp => new QuoteCache(sp.GetRequiredService<TradingDbContext>())) pass ValidateOnBuild?
    The build-time walk treats a factory registration as a black box; it cannot see which services the lambda will request. The lambda runs on first resolution with the root provider, so `ValidateScopes` throws "Cannot resolve scoped service 'TradingDbContext' from root provider." then, and with validation off the context is silently captured.
  • What changed for the generic HostBuilder in .NET 9?
    Before .NET 9 a hand-built `HostBuilder` used plain `ServiceProviderOptions` with both checks off unless you called `UseDefaultServiceProvider`. Since .NET 9 it enables `ValidateScopes` and `ValidateOnBuild` in Development when you have not configured the provider yourself, matching `WebApplicationBuilder` and `Host.CreateDefaultBuilder`.

  • Scope validation is on in every environment, so Production catches captives too.
  • ValidateOnBuild instantiates every singleton at startup to test it.
  • ValidateOnBuild also sees the services a factory lambda resolves.
  • ValidateScopes catches a scoped DbContext disposed early by a fire-and-forget task.
  • Once ValidateOnBuild passes in Development, no lifetime error can occur later.

Assumes ASP.NET Core 10 on .NET 10; the generic HostBuilder has enabled both checks in Development since .NET 9, while WebApplicationBuilder already did.