Join Nostr
2026-10-27 12:38:11 UTC

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