Create various scopes - forgot that EF Core DBContexts don't work in a singleton service
This commit is contained in:
parent
37841db663
commit
9974bb5f0c
|
|
@ -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<GeoFeedCacheService> logger;
|
||||
private readonly IGeoFeedProvider feedProvider;
|
||||
private readonly GeoFeedCacheDbContext dbContext;
|
||||
private readonly IHost host;
|
||||
|
||||
public GeoFeedCacheService(ILogger<GeoFeedCacheService> 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<bool> StartPerioidicSync()
|
||||
{
|
||||
if (dbContext.Database.GetPendingMigrations().Any())
|
||||
await dbContext.Database.MigrateAsync();
|
||||
await DBContextMigrate();
|
||||
|
||||
List<GeoFeedCacheEntry> 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<GeoFeedCacheDbContext>();
|
||||
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<GeoFeedCacheDbContext>();
|
||||
if (dbContext.Database.GetPendingMigrations().Any())
|
||||
{
|
||||
await dbContext.Database.MigrateAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue