BuildServiceProvider is called while services are still being registered, which creates a second container
What it finds
Calling services.BuildServiceProvider() during registration builds a separate container with its own singletons: a singleton resolved from it is a different instance from the one the app uses later, and scoped services resolved from it are never disposed. Options callbacks, factories that take an IServiceProvider, or IConfigureOptions<T> get services from the app's container instead. The rule reports the call in files that use Microsoft.Extensions.DependencyInjection, inside ConfigureServices or followed by further registrations on the same collection; building the final provider is fine.
From the rule's source, second_service_provider.rs.
using Microsoft.Extensions.DependencyInjection; class Startup{ void ConfigureServices(IServiceCollection services) { var provider = services.BuildServiceProvider();tx0 reports: a second service container is built during registration services.AddSingleton(provider.GetRequiredService<Clock>()); }} class Clock{} Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/csharp:second-service-provider" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/csharp:second-service-provider] reason="..."tx0 explain tx0/csharp:second-service-provider shows the same in the terminal. Found a false positive? Report it.