2022-02-13 17:12:00 +00:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
using Microsoft.Extensions.Hosting;
|
2022-02-16 23:38:45 +00:00
|
|
|
|
using Microsoft.Extensions.DependencyInjection;
|
2022-02-13 17:12:00 +00:00
|
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
using Microsoft.Extensions.Options;
|
2022-02-16 23:38:45 +00:00
|
|
|
|
using System;
|
2022-02-13 17:12:00 +00:00
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace Selector.Model.Services
|
|
|
|
|
{
|
|
|
|
|
public class MigratorService : IHostedService
|
|
|
|
|
{
|
2022-02-16 23:38:45 +00:00
|
|
|
|
private readonly IServiceScopeFactory scopeProvider;
|
2022-02-13 17:12:00 +00:00
|
|
|
|
private readonly DatabaseOptions options;
|
|
|
|
|
private readonly ILogger<MigratorService> logger;
|
|
|
|
|
|
2022-02-16 23:38:45 +00:00
|
|
|
|
public MigratorService(IServiceScopeFactory _scopeProvider, IOptions<DatabaseOptions> _options, ILogger<MigratorService> _logger)
|
2022-02-13 17:12:00 +00:00
|
|
|
|
{
|
2022-02-16 23:38:45 +00:00
|
|
|
|
scopeProvider = _scopeProvider;
|
2022-02-13 17:12:00 +00:00
|
|
|
|
options = _options.Value;
|
|
|
|
|
logger = _logger;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Task StartAsync(CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
if(options.Migrate)
|
|
|
|
|
{
|
2022-02-16 23:38:45 +00:00
|
|
|
|
using var scope = scopeProvider.CreateScope();
|
|
|
|
|
|
2022-02-13 17:12:00 +00:00
|
|
|
|
logger.LogInformation("Applying migrations");
|
2022-02-16 23:38:45 +00:00
|
|
|
|
scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
|
2022-02-13 17:12:00 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
return Task.CompletedTask;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|