Member-only story
How to Use a Scoped Service Inside a Hosted Service in .NET
Avoid common dependency injection mistakes and build clean, reliable background jobs in .NET using IServiceScopeFactory
When building .NET applications, you might need to run background processes that work independently of user requests. Examples include sending periodic emails, syncing data with external systems, or cleaning old records from a database. The recommended way to handle such background work in .NET is by using a Hosted Service.
However, one common problem developers face when working with hosted services is using scoped services inside them. Also, this is a popular interview question for .NET Developers. For instance, if your background task needs access to a DbContext, a repository or any service registered as scoped, you will quickly discover that you cannot inject it directly into a hosted service. This limitation exists because of how the dependency injection (DI) container in .NET manages service lifetimes.
Let’s look at why this problem happens, and then we’ll go through a proper solution with a detailed example.
