CodexBloom - Programming Q&A Platform

Error with Dependency Injection Lifetime Scopes in ASP.NET Core 6 Causing Object Disposal Issues

πŸ‘€ Views: 263 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-07
asp.net-core dependency-injection background-service C#

I'm having trouble with the dependency injection setup in my ASP.NET Core 6 application. I registered a service with a scoped lifetime, but I'm encountering an `ObjectDisposedException` when trying to access this service from a background task that's created in a singleton service. 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 myService = scope.ServiceProvider.GetRequiredService<IMyScopedService>(); await myService.DoWorkAsync(); // This line throws ObjectDisposedException } await Task.Delay(1000, stoppingToken); } } } public interface IMyScopedService { Task DoWorkAsync(); } public class MyScopedService : IMyScopedService { public Task DoWorkAsync() { // Some work... return Task.CompletedTask; } } ``` I've confirmed that `IMyScopedService` is registered as scoped in my `Startup.cs`: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddScoped<IMyScopedService, MyScopedService>(); services.AddHostedService<MyBackgroundService>(); } ``` The exception occurs when `DoWorkAsync` is called, indicating that the scoped service has been disposed. I attempted to move the service registration to singleton, but that leads to other issues since the service itself relies on scoped dependencies. I’ve also checked for any incorrect calls to the service outside of the expected lifetime but haven’t found any. What could be the reason for this `ObjectDisposedException` in my scenario? How can I resolve this issue while maintaining scoped lifetimes appropriately?