CodexBloom - Programming Q&A Platform

ASP.NET Core 6: solution with Async Calls and Scoped Services in Background Tasks

👀 Views: 82 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-14
asp.net-core background-tasks dependency-injection csharp

I've encountered a strange issue with I'm working on a personal project and I'm integrating two systems and I'm working with a question with using scoped services in background tasks with ASP.NET Core 6... I've set up a hosted service that processes background jobs, and within that service, I'm trying to inject a scoped service to fetch some data from the database. However, I'm running into an `InvalidOperationException` with the message: `want to resolve scoped service 'MyApp.Services.IMyScopedService' from root provider.` Here's a snippet of my hosted service implementation: ```csharp public class MyBackgroundService : BackgroundService { private readonly IServiceScopeFactory _serviceScopeFactory; public MyBackgroundService(IServiceScopeFactory serviceScopeFactory) { _serviceScopeFactory = serviceScopeFactory; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { using (var scope = _serviceScopeFactory.CreateScope()) { var myScopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>(); await myScopedService.ProcessDataAsync(); } await Task.Delay(1000, stoppingToken); } } } ``` I've registered `IMyScopedService` in my `Startup.cs` like this: ```csharp services.AddScoped<IMyScopedService, MyScopedService>(); services.AddHostedService<MyBackgroundService>(); ``` I thought creating a scope within the background service would solve the question, but it seems like the service is not being resolved correctly. I've also double-checked that `IMyScopedService` is not registered as a singleton or transient. What am I missing here? Is there a better approach to handle scoped services within background tasks in ASP.NET Core? I'm working on a desktop app that needs to handle this. This is part of a larger desktop app I'm building. I'm open to any suggestions. This is part of a larger web app I'm building. Thanks for any help you can provide!