How to implement guide with asp.net core 6 dependency injection for scoped services in background tasks
I'm refactoring my project and I'm integrating two systems and Hey everyone, I'm running into an issue that's driving me crazy... I'm currently working on an ASP.NET Core 6 application and I've encountered a question with dependency injection when using scoped services in background tasks. I'm trying to use a scoped service within a hosted service to perform operations in the background, but I keep running into the behavior: `InvalidOperationException: want to resolve scoped service 'MyApp.Services.IMyScopedService' from root provider.` I've tried to follow the best practices mentioned in the documentation, but I'm still having trouble. Hereβs how I set up my `IMyScopedService`: ```csharp public interface IMyScopedService { Task DoWorkAsync(); } public class MyScopedService : IMyScopedService { public async Task DoWorkAsync() { // Implementation of the work } } ``` I then registered it in `Startup.cs` like this: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddScoped<IMyScopedService, MyScopedService>(); services.AddHostedService<MyBackgroundService>(); } ``` Next, I have my background service: ```csharp public class MyBackgroundService : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; public MyBackgroundService(IServiceScopeFactory scopeFactory) { _scopeFactory = scopeFactory; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { using (var scope = _scopeFactory.CreateScope()) { var scopedService = scope.ServiceProvider.GetRequiredService<IMyScopedService>(); await scopedService.DoWorkAsync(); } await Task.Delay(1000, stoppingToken); } } } ``` The behavior occurs when I attempt to resolve `IMyScopedService` inside `MyBackgroundService`. I thought that creating a new scope would allow me to use the scoped service correctly, but it seems like the service provider isn't able to resolve it. I've also checked that the `MyScopedService` does not have any constructor dependencies that are registered with a shorter lifecycle. Could this be an scenario with the way I'm setting up my services, or is there something specific to the hosted service's lifecycle that I am missing? Any guidance would be appreciated! Thanks in advance! This is part of a larger CLI tool I'm building. Any ideas what could be causing this?