namespace marlin.web.Services; using Data; using Microsoft.EntityFrameworkCore; public class DatabaseUpgrader : IHostedService { private readonly ILogger _logger; private readonly IServiceProvider _serviceProvider; public DatabaseUpgrader(ILogger logger, IServiceProvider serviceProvider) { this._logger = logger; this._serviceProvider = serviceProvider; } public async Task StartAsync(CancellationToken ct) { await using AsyncServiceScope scope = this._serviceProvider.CreateAsyncScope(); DbContext dbContext = scope.ServiceProvider.GetRequiredService(); var migrations = await dbContext.Database.GetPendingMigrationsAsync(ct); int pendingCount = migrations.Count(); if (pendingCount == 0) { this._logger.LogInformation("Database is up to date."); return; } this._logger.LogInformation("Upgrading database {count} versions.", pendingCount); try { await dbContext.Database.MigrateAsync(ct); this._logger.LogInformation("Database upgraded."); } catch (Exception ex) { this._logger.LogError(ex, "Database upgrade failed, {count} behind.", pendingCount); } } public Task StopAsync(CancellationToken ct) => Task.CompletedTask; }