|
| 1 | +using System.Diagnostics; |
| 2 | +using Microsoft.EntityFrameworkCore; |
| 3 | +using PocketDDD.Server.DB; |
| 4 | +using PocketDDD.Server.Model.DBModel; |
| 5 | + |
| 6 | +namespace PocketDDD.Server.MigrationService; |
| 7 | + |
| 8 | +public class Worker( |
| 9 | + IServiceProvider serviceProvider, |
| 10 | + IHostApplicationLifetime lifetime, |
| 11 | + ILogger<Worker> logger) : BackgroundService |
| 12 | +{ |
| 13 | + public const string ActivitySourceName = "PocketDDD.Migrations"; |
| 14 | + |
| 15 | + private static readonly ActivitySource ActivitySource = new(ActivitySourceName); |
| 16 | + |
| 17 | + protected override async Task ExecuteAsync(CancellationToken stoppingToken) |
| 18 | + { |
| 19 | + using var activity = ActivitySource.StartActivity("Migrating database", ActivityKind.Client); |
| 20 | + |
| 21 | + try |
| 22 | + { |
| 23 | + using var scope = serviceProvider.CreateScope(); |
| 24 | + var db = scope.ServiceProvider.GetRequiredService<PocketDDDContext>(); |
| 25 | + |
| 26 | + await RunMigrationAsync(db, stoppingToken); |
| 27 | + await SeedAsync(db, stoppingToken); |
| 28 | + } |
| 29 | + catch (Exception ex) |
| 30 | + { |
| 31 | + activity?.AddException(ex); |
| 32 | + logger.LogError(ex, "Database migration failed."); |
| 33 | + throw; |
| 34 | + } |
| 35 | + |
| 36 | + lifetime.StopApplication(); |
| 37 | + } |
| 38 | + |
| 39 | + private static Task RunMigrationAsync(PocketDDDContext db, CancellationToken cancellationToken) |
| 40 | + { |
| 41 | + var strategy = db.Database.CreateExecutionStrategy(); |
| 42 | + return strategy.ExecuteAsync(() => db.Database.MigrateAsync(cancellationToken)); |
| 43 | + } |
| 44 | + |
| 45 | + private static async Task SeedAsync(PocketDDDContext db, CancellationToken cancellationToken) |
| 46 | + { |
| 47 | + if (await db.EventDetail.AnyAsync(cancellationToken)) return; |
| 48 | + |
| 49 | + db.EventDetail.Add(new EventDetail { SessionizeId = "dev-event", Version = 0 }); |
| 50 | + await db.SaveChangesAsync(cancellationToken); |
| 51 | + } |
| 52 | +} |
0 commit comments