codementor on Nostr: Learn: Scoped services in a singleton or BackgroundService A BackgroundService is a ...
Learn: Scoped services in a singleton or BackgroundService
A BackgroundService is a singleton, but a DbContext is scoped. Injecting the DbContext directly would keep one DbContext forever.
Fix: inject IServiceScopeFactory. For each piece of work: create a scope, get the DbContext from it, and dispose the scope when done.
In Development, ASP.NET Core checks this for you (scope validation) and throws at startup if a singleton depends on a scoped service.
Read more:
https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#tip · TIP-096
Published at
2026-10-27 12:38:11 UTCEvent JSON
{
"id": "c78c7bfd4432a615aa9d8e90915da3ccaa74fa859cc7261316dc01d2c3b0f3be",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1793104691,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Scoped services in a singleton or BackgroundService\n\nA BackgroundService is a singleton, but a DbContext is scoped. Injecting the DbContext directly would keep one DbContext forever.\nFix: inject IServiceScopeFactory. For each piece of work: create a scope, get the DbContext from it, and dispose the scope when done.\nIn Development, ASP.NET Core checks this for you (scope validation) and throws at startup if a singleton depends on a scoped service.\n\nRead more: https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection\n\n#tip · TIP-096",
"sig": "a6b165cb30bd6bed99785fe2c639f7c87ebb671a630cc69a654e28f2469d0d2d6615b5467c2a80181c861ba5f6f12276ff6ec077d5f80af8a86cd32a1c4e3ebf"
}