CodexBloom - Programming Q&A Platform

C# - implementing Scoped Services and Background Tasks in ASP.NET Core 6

👀 Views: 93 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-22
aspnet-core background-tasks dependency-injection C#

I'm refactoring my project and I'm performance testing and I'm deploying to production and I'm working with a question with scoped services when using them in background tasks in my ASP.NET Core 6 application..... I have a hosted service that runs a background task, and it seems to lose access to the scoped services injected into it. Here's a simplified version of my code: ```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.DoWorkAsync(); } await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); } } } ``` In my `IMyScopedService`, I have a method `DoWorkAsync` that relies on some database operations. However, I'm getting an `InvalidOperationException`: "want to consume scoped service 'MyDbContext' from singleton 'IMyScopedService'". I understand that the scenario arises because `IMyScopedService` is registered as a singleton, and it's trying to use a scoped service, which is generally not allowed. I've tried changing the registration of `IMyScopedService` to be scoped: ```csharp services.AddScoped<IMyScopedService, MyScopedService>(); ``` But then I'm unable to resolve it in `MyBackgroundService`, which requires it to be a singleton since `BackgroundService` itself is a singleton. How can I properly manage the lifecycle of my services in this scenario, so that I can use `IMyScopedService` without running into the scoped vs singleton issues? Are there any best practices for handling this scenario? For context: I'm using C# on Windows. How would you solve this? The stack includes C# and several other technologies. Has anyone else encountered this?