services.BuildServiceProvider() takes a snapshot of the IServiceCollection and builds a second, independent root container. It has its own singleton cache, so every singleton resolved from it is a different instance from the app's (two caches, two connection pools); nothing disposes it, so its singletons and root-resolved disposables leak; registrations added later are missing; and scoped services resolved from its root effectively live for ever. The ASP0000 analyser warns about it.
Instead, defer the work until the real container exists:
sp => new Foo(sp.GetRequiredService<IBar>()), which runs on first resolution from the real provider;IConfigureOptions<T> (or AddOptions<T>().Configure<IDep>(...)) for options that need services;builder.Build() for start-up work.Trade-off: deferring moves failures from start-up to first use, so pair it with ValidateOnBuild.
"
BuildServiceProvider()doesn't give you 'the' container, it builds another one from whatever is in the collection at that moment. That second root provider has its own singleton cache, so if I resolve a cache or anHttpClienthandler from it, the app later gets a different instance from the real provider. Nobody disposes the second provider, so its singletons and any transient disposables resolved from its root stay alive until the process exits. Anything registered after the call simply isn't there, and a scoped service resolved from that root is effectively a singleton.The fix is to not need the container while you're still registering. If a registration needs another service, I use a factory delegate, which runs later against the real provider. If options need a service, I write an
IConfigureOptions<T>. If I need to run something at start-up, like warming a cache or migrating a database in development, I do it afterbuilder.Build()in a scope, or in a hosted service. ASP0000 catches the call, and I treat that warning as an error."
| Effect | Why |
|---|---|
| Duplicate singletons | Each root provider caches its own singleton instances |
| Leaks | The extra provider is never disposed, so its disposables never are either |
| Missing registrations | It is a snapshot; later Add* calls don't reach it |
| Scoped acting as singleton | Resolved from a root with no scope (and scope validation not applied) |
| Need | Use |
|---|---|
| A service to construct another | services.AddSingleton<IFoo>(sp => new Foo(sp.GetRequiredService<IBar>())) |
| Options that depend on a service | IConfigureOptions<T> or AddOptions<T>().Configure<IDep>((o, dep) => ...) |
| Start-up work | using var scope = app.Services.CreateScope(); after Build(), or IHostedService |
Checks awareness of duplicate singleton containers and ASP0000
Last updated 23 Nov 2026.