blob: 1ae13724525ed20c790e4fd626106052f64e9e09 (
plain)
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
|
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
using Timeline.Configs;
using Timeline.Entities;
namespace Timeline.Services.DatabaseManagement
{
public class DatabaseManagementService : IHostedService
{
private readonly ILogger<DatabaseManagementService> _logger;
private readonly IServiceProvider _serviceProvider;
private readonly bool _disableAutoBackup;
public DatabaseManagementService(IServiceProvider serviceProvider, IConfiguration configuration, ILogger<DatabaseManagementService> logger)
{
_serviceProvider = serviceProvider;
_disableAutoBackup = ApplicationConfiguration.GetBoolConfig(configuration, ApplicationConfiguration.DisableAutoBackupKey, false);
_logger = logger;
}
public async Task StartAsync(CancellationToken cancellationToken = default)
{
using var scope = _serviceProvider.CreateScope();
var provider = scope.ServiceProvider;
var backupService = provider.GetRequiredService<IDatabaseBackupService>();
var database = provider.GetRequiredService<DatabaseContext>();
var customMigrator = provider.GetRequiredService<IDatabaseCustomMigrator>();
if (!_disableAutoBackup)
{
await backupService.BackupAsync(cancellationToken);
}
else
{
_logger.LogWarning("Auto backup is disabled. Please backup your database manually.");
}
await database.Database.MigrateAsync(cancellationToken);
await customMigrator.MigrateAsync(cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
}
|