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).
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.
"They catch different classes of mistakes at different times.
ValidateScopesis about lifetimes. When a call site is resolved, the provider checks whether a singleton depends, directly or transitively, on something scoped, and throwsCannot 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 callsapp.Services.GetRequiredService<AppDbContext>()at start-up. Without it, both mistakes silently create a captive instance that lives forever.
ValidateOnBuildis about completeness. AtBuild()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 oneAggregateExceptionlisting each failing service. Combined withValidateScopes, captive dependencies also fail at start-up instead of on first use.
WebApplication.CreateBuildersets both toIsDevelopment(). 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 captiveDbContextcorrupts data quietly. I also know their limits: dependencies inside a factory lambda, open generics and anything resolved throughIServiceProviderin code aren't checked."
| 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() |
| 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 |
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.
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
ValidateScopes errors and the build-time AggregateExceptionIsDevelopment() default and how to override itRed flags
ValidateOnBuild instantiates every servicenew 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)).
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.
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.
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.
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.
ValidateOnBuild.ValidateOnBuild no longer reports it.WebApplicationFactory test with UseEnvironment("Production") and UseDefaultServiceProvider forcing both options on.ValidateOnBuild using dotnet-counters or a Stopwatch around builder.Build().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>());
}
}
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.ValidateOnBuild covers factory registrations. Why it is wrong: dependencies resolved inside the lambda are invisible. Instead: prefer type registrations and test-resolve factory services.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.UseEnvironment("Production") with test-safe configuration.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.
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.
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.
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:
sp => ...): the body is opaque code that only runs on resolution;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.
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.
Last updated 23 Nov 2026.