CodexBloom - Programming Q&A Platform

C# - Difficulty with Dependency Injection in ASP.NET Core for Scoped Services in Background Tasks

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

I'm trying to debug I'm working on a personal project and I'm having trouble with dependency injection in my ASP.NET Core application, specifically when trying to use a scoped service within a background task. I have a service `MyScopedService` that is registered as scoped in my `Startup.cs`: ```csharp services.AddScoped<MyScopedService>(); ``` In one of my controllers, I start a background task like this: ```csharp public class MyController : ControllerBase { private readonly MyScopedService _myScopedService; public MyController(MyScopedService myScopedService) { _myScopedService = myScopedService; } [HttpPost] public async Task<IActionResult> StartBackgroundTask() { await Task.Run(() => BackgroundTask()); return Ok(); } private void BackgroundTask() { // Access scoped service here _myScopedService.DoSomething(); } } ``` However, I'm getting an `InvalidOperationException` with the message: "Cannot resolve scoped service `MyScopedService` from root provider." This leads me to believe that the context in which `BackgroundTask` is running does not have access to the scoped service. I've tried changing the way I start the background task by using `IServiceScopeFactory` to create a new scope: ```csharp private readonly IServiceScopeFactory _serviceScopeFactory; public MyController(MyScopedService myScopedService, IServiceScopeFactory serviceScopeFactory) { _myScopedService = myScopedService; _serviceScopeFactory = serviceScopeFactory; } private void BackgroundTask() { using (var scope = _serviceScopeFactory.CreateScope()) { var scopedService = scope.ServiceProvider.GetRequiredService<MyScopedService>(); scopedService.DoSomething(); } } ``` While this approach resolves the exception, I've noticed that the background task behaves inconsistently when called multiple times. Sometimes it seems to execute correctly, while other times it appears to drop requests silently, or I get a timeout if the task takes too long. Is there a best practice for handling scoped services in background tasks in ASP.NET Core? How can I ensure that my background tasks run reliably and consistently using scoped services? I'm working on a application that needs to handle this. Is there a better approach? The stack includes C# and several other technologies. Thanks for taking the time to read this!