-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathWorker.cs
55 lines (48 loc) · 1.88 KB
/
Worker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using DrawTogether.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
namespace DrawTogether.MigrationService;
public class Worker(
IServiceProvider serviceProvider,
IHostApplicationLifetime hostApplicationLifetime,
ILogger<Worker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
using var scope = serviceProvider.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await EnsureCreatedAsync(dbContext, stoppingToken);
await RunMigrationAsync(dbContext, stoppingToken);
}
catch (Exception ex)
{
logger.LogError(ex, "An error occurred while migrating the database");
}
hostApplicationLifetime.StopApplication();
}
private async Task EnsureCreatedAsync(ApplicationDbContext dbContext, CancellationToken cancellationToken)
{
var strategy = dbContext.Database.CreateExecutionStrategy();
var databaseCreator = dbContext.Database.GetService<IRelationalDatabaseCreator>();
await strategy.ExecuteAsync(async ct =>
{
if (!await databaseCreator.ExistsAsync(ct))
{
await databaseCreator.CreateAsync(ct);
logger.LogInformation("Database created");
}
}, cancellationToken);
}
private async Task RunMigrationAsync(ApplicationDbContext dbContext, CancellationToken cancellationToken)
{
var strategy = dbContext.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async ct =>
{
await dbContext.Database.MigrateAsync(ct);
logger.LogInformation("Database migrated");
}, cancellationToken);
}
}