From b40e394bcf115f562a1f1de48ac4c4a252fa3d52 Mon Sep 17 00:00:00 2001 From: Polianin Nikita Date: Mon, 3 Feb 2025 10:55:47 +0300 Subject: [PATCH] fix: System.ObjectDisposedException for db context into sync secrvice --- .../V1/Configuration/ScheduleController.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Endpoint/Controllers/V1/Configuration/ScheduleController.cs b/Endpoint/Controllers/V1/Configuration/ScheduleController.cs index 178704b..6191c6d 100644 --- a/Endpoint/Controllers/V1/Configuration/ScheduleController.cs +++ b/Endpoint/Controllers/V1/Configuration/ScheduleController.cs @@ -2,6 +2,7 @@ using Cronos; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; @@ -191,15 +192,20 @@ public class ScheduleController(ILogger logger, IOptionsSnap filePaths.Add((filePath, defaultCampus[i])); } - var sync = (ScheduleSynchronizer)ActivatorUtilities.GetServiceOrCreateInstance(provider, typeof(ScheduleSynchronizer)); - if (force) { - dbContext.Lessons.RemoveRange(dbContext.Lessons.ToList()); + dbContext.Lessons.RemoveRange(await dbContext.Lessons.ToListAsync()); await dbContext.SaveChangesAsync(); } - _ = sync.StartSync(filePaths, CancellationToken.None); + var scopeFactory = provider.GetRequiredService(); + _ = Task.Run(async () => + { + using var scope = scopeFactory.CreateScope(); + var sync = scope.ServiceProvider.GetRequiredService(); + + await sync.StartSync(filePaths, CancellationToken.None); + }, CancellationToken.None); return Ok(); }