I'm trying to create a method in the web api controller (ASP.NET Core 6 Web Api) that will accept the request, register it in the queue, return the HTTP code 200, and the request will be processed in the background. After processing the request, I plan to send information about it using SignalR. I created a BackgroundService for this purpose. Unfortunately, I don't know how to get autofac to work properly with this solution. When I try to call the method (which works when I do it with await and without BackgroundService) I get an error message:
Microsoft.Extensions.Hosting.Internal.Host[9]
BackgroundService failed
System.ObjectDisposedException: Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'RepositoryManagerDbContext'.
at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
at Microsoft.EntityFrameworkCore.DbContext.get_ContextServices()
at Microsoft.EntityFrameworkCore.DbContext.get_Model()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
at RepositoryManager.Configuration.Services.ConfigurationService.GetConfigValueByType(RmConfigType type) in C:\GIT\repositoryManager\RepositoryManager\RepositoryManager.Configuration\Services\ConfigurationService.cs:line 36
at RepositoryManager.Repository.Services.RepositoryService.PrepareRepositoryPath(String taskNumber, String appName) in C:\GIT\repositoryManager\RepositoryManager\RepositoryManager.Repository\Services\RepositoryService.cs:line 52
at RepositoryManager.Repository.Services.RepositoryService.CreateDeveloperEnvironment(SaveTaskDto dto) in C:\GIT\repositoryManager\RepositoryManager\RepositoryManager.Repository\Services\RepositoryService.cs:line 31
at RepositoryManager.Controllers.TaskController.CreateDeveloperEnvironmentAndNotify(SaveTaskDto request) in C:\GIT\repositoryManager\RepositoryManager\RepositoryManager\Controllers\TaskController.cs:line 33
at BackgroundTaskService.ExecuteAsync(CancellationToken stoppingToken) in C:\GIT\repositoryManager\RepositoryManager\RepositoryManager\BackgroundTaskService.cs:line 18
at BackgroundTaskService.ExecuteAsync(CancellationToken stoppingToken) in C:\GIT\repositoryManager\RepositoryManager\RepositoryManager\BackgroundTaskService.cs:line 15
at Microsoft.Extensions.Hosting.Internal.Host.TryExecuteBackgroundServiceAsync(BackgroundService backgroundService)
in Startup.cs I registered the modules:
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterType<BackgroundTaskService>().AsSelf().As<IHostedService>().SingleInstance();
builder.RegisterModule<DatabaseModule>();
builder.RegisterModule<GitModule>();
builder.RegisterModule<ConfigurationModule>();
builder.RegisterModule<RedmineModule>();
builder.RegisterModule<ExternalPerspectivModule>();
builder.RegisterModule<RepositoryModule>();
builder.RegisterModule<DiskModule>();
builder.RegisterType<SignalRHub>();
}
Database registration in DatabaseModule:
builder.RegisterType<RepositoryManagerDbContext>().AsSelf().InstancePerLifetimeScope();
My BackgroundTaskService:
public class BackgroundTaskService : BackgroundService
{
private readonly Channel<BackgroundTask> taskQueue;
public BackgroundTaskService()
{
taskQueue = Channel.CreateUnbounded<BackgroundTask>();
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var backgroundTask in taskQueue.Reader.ReadAllAsync(stoppingToken))
{
Console.WriteLine($"Starting task {backgroundTask.Id}");
await backgroundTask.Task();
Console.WriteLine($"Completed task {backgroundTask.Id}");
}
}
public async Task EnqueueTask(Func<Task> task)
{
var backgroundTask = new BackgroundTask { Task = task };
Console.WriteLine($"Enqueueing task {backgroundTask.Id}");
await taskQueue.Writer.WriteAsync(backgroundTask);
}
}
(BackgroundTask class has 2 properties: Func and Guid).
Now in Controller I'm adding to the queue:
[HttpPost]
public async Task<IActionResult> CreateTaskRepo(SaveTaskDto request)
{
backgroundTaskService.EnqueueTask(() => CreateDeveloperEnvironmentAndNotify(request));
return Ok();
}
private async Task CreateDeveloperEnvironmentAndNotify(SaveTaskDto request)
{
await repoService.CreateDeveloperEnvironment(request);
await hubContext.Clients.All.SendAsync("ReceiveMessage", "CreateTaskRepo", new { Status = "Completed" });
}
(repoService is injectet in Controller constructor)
I suspect that the error appears because the controller has already responded to the request, but I don't know how to fix it to make it work. A polite request for help.