From 9974bb5f0c113f5e4fa984c2ae04239acced51e7 Mon Sep 17 00:00:00 2001 From: Jeff Leung Date: Mon, 8 Jan 2024 10:08:28 -0800 Subject: [PATCH] Create various scopes - forgot that EF Core DBContexts don't work in a singleton service --- .../GeoFeedLocalCache/GeoFeedCacheService.cs | 24 +++++++++++++++---- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/AS1024.GeoFeed/GeoFeedLocalCache/GeoFeedCacheService.cs b/AS1024.GeoFeed/GeoFeedLocalCache/GeoFeedCacheService.cs index 48dde93..60127da 100644 --- a/AS1024.GeoFeed/GeoFeedLocalCache/GeoFeedCacheService.cs +++ b/AS1024.GeoFeed/GeoFeedLocalCache/GeoFeedCacheService.cs @@ -1,5 +1,6 @@ using AS1024.GeoFeed.Interfaces; using Microsoft.EntityFrameworkCore; +using System.Runtime.CompilerServices; namespace AS1024.GeoFeed.GeoFeedLocalCache { @@ -8,15 +9,15 @@ namespace AS1024.GeoFeed.GeoFeedLocalCache CancellationToken _cancellationToken; private readonly ILogger logger; private readonly IGeoFeedProvider feedProvider; - private readonly GeoFeedCacheDbContext dbContext; + private readonly IHost host; public GeoFeedCacheService(ILogger logger, IGeoFeedProvider feedProvider, - GeoFeedCacheDbContext dbContext) + IHost host) { this.logger = logger; this.feedProvider = feedProvider; - this.dbContext = dbContext; + this.host = host; } public Task StartAsync(CancellationToken cancellationToken) @@ -32,8 +33,7 @@ namespace AS1024.GeoFeed.GeoFeedLocalCache public async Task StartPerioidicSync() { - if (dbContext.Database.GetPendingMigrations().Any()) - await dbContext.Database.MigrateAsync(); + await DBContextMigrate(); List geoFeedCacheEntry = []; while (!_cancellationToken.IsCancellationRequested) @@ -42,6 +42,8 @@ namespace AS1024.GeoFeed.GeoFeedLocalCache logger.LogInformation("Running on disk fallback cache process..."); try { + using var scope = host.Services.CreateScope(); + using var dbContext = scope.ServiceProvider.GetRequiredService(); var results = await feedProvider.GetGeoFeedData(); results.ForEach(x => @@ -69,7 +71,19 @@ namespace AS1024.GeoFeed.GeoFeedLocalCache logger.LogWarning("On disk cache failed to run. Waiting on 30 minutes before retry..."); } } + return false; } + + private async Task DBContextMigrate() + { + using IServiceScope scope = host.Services.CreateScope(); + using GeoFeedCacheDbContext? dbContext = + host.Services.GetService(); + if (dbContext.Database.GetPendingMigrations().Any()) + { + await dbContext.Database.MigrateAsync(); + } + } } } \ No newline at end of file