An Entity Framework DbContext is registered as a singleton, though it is not thread-safe
What it finds
A DbContext tracks the entities it loaded and allows one operation at a time. As a singleton it is shared by all requests at once, which throws on concurrent use, and its change tracker grows for the lifetime of the app. AddDbContext registers it per scope; AddDbContextFactory gives singletons a way to create short-lived contexts.
From the rule's source, singleton_db_context.rs.
using Microsoft.Extensions.DependencyInjection; class Startup{ void ConfigureServices(IServiceCollection services) { services.AddSingleton<ShopDbContext>();tx0 reports: ShopDbContext is registered as a singleton services.AddSingleton<Clock>(); }} class ShopDbContext{} 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:singleton-db-context" = "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:singleton-db-context] reason="..."tx0 explain tx0/csharp:singleton-db-context shows the same in the terminal. Found a false positive? Report it.