C# Dependency Injection: Scoped Services Not Resolving in Background Hosted Service
I'm a bit lost with I've been working on this all day and I've been banging my head against this for hours. I'm working with an scenario with dependency injection in my .NET 6 application. I'm using a background hosted service to perform periodic tasks, but I'm having trouble resolving scoped services within that context. Specifically, when I attempt to inject a DbContext (which is registered as a scoped service) into my hosted service, I get an `InvalidOperationException` with the message: `want to resolve scoped service 'MyApp.Data.MyDbContext' from root provider.` Here's a simplified version of my setup: ```csharp public class MyDbContext : DbContext { public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { } } public class MyHostedService : IHostedService { private readonly IServiceScopeFactory _scopeFactory; public MyHostedService(IServiceScopeFactory scopeFactory) { _scopeFactory = scopeFactory; } public async Task StartAsync(CancellationToken cancellationToken) { using (var scope = _scopeFactory.CreateScope()) { var dbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>(); // Perform database operations } } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; } ``` In my `Startup.cs`, I'm registering my services like this: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddHostedService<MyHostedService>(); } ``` I thought that creating a scope within `StartAsync` would allow me to resolve the scoped `DbContext`, but it seems like the service lifetime configuration isn't behaving as expected. I've tried moving the service registration order around and ensuring that I create the scope directly where I need the `DbContext`, but the behavior continues. Has anyone encountered this question before, or can someone point me in the right direction? Any insights or workarounds would be appreciated! Is there a better approach? Any ideas what could be causing this? What's the correct way to implement this?