ASP.NET Core & Web API (50 Qs)•Part 1: Request Pipeline, Dependency Injection & Web APIs (1 - 10)
How do you implement Background Services (`IHostedService` & `BackgroundService`)?
mid LevelMost AskedDependency InjectionPipesCI/CD & DevOps
In Simple Words:
Implement BackgroundService to run long-running background workers, queue consumers, or scheduled jobs inside ASP.NET Core:
- Executes
ExecuteAsync(CancellationToken stoppingToken)in a background thread. - Important: To use scoped services (like
DbContext) inside a singleton background worker, you must manually create a scope viaIServiceScopeFactory.CreateScope().