seniorDependency Injection
How do you manage DI in Background Services / Hosted Services?
Updated Apr 28, 2026
Short answer
Background services run independently of user requests and usually operate as Singletons. This creates friction when they need Scoped dependencies.
Deep explanation
To use a database (Scoped) inside a background worker (Singleton), the worker must explicitly create a new dependency scope using a Scope Factory. It resolves the Scoped services, performs the work, and ensures the scope is disposed properly to release the resources.
Unlock with a Pro subscription to view this section.
View pricingReal-world example
No real-world example available yet.
Unlock with a Pro subscription to view this section.
Upgrade to ProCommon mistakes
No common mistakes listed yet.
Unlock with a Pro subscription to view this section.
Upgrade to ProFollow-up questions
No follow-up questions available yet.
Unlock with a Pro subscription to view this section.
Upgrade to Pro