2022-01-04 08:42:12 +00:00
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
|
using Microsoft.Extensions.Hosting;
|
|
|
|
|
|
|
2023-01-04 19:36:38 +00:00
|
|
|
|
namespace Elsa.EntityFrameworkCore.Common;
|
2022-01-04 08:42:12 +00:00
|
|
|
|
|
2023-01-04 19:36:38 +00:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// Executes EF Core migrations using the specified <see cref="DbContext"/> type.
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public class RunMigrationsHostedService<TDbContext> : IHostedService where TDbContext : DbContext
|
|
|
|
|
|
{
|
|
|
|
|
|
private readonly IDbContextFactory<TDbContext> _dbContextFactory;
|
2023-05-28 14:40:10 +00:00
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// Initializes a new instance of the <see cref="RunMigrationsHostedService{TDbContext}"/> class.
|
|
|
|
|
|
/// </summary>
|
2023-01-04 19:36:38 +00:00
|
|
|
|
public RunMigrationsHostedService(IDbContextFactory<TDbContext> dbContextFactoryFactory) => _dbContextFactory = dbContextFactoryFactory;
|
2022-01-04 08:42:12 +00:00
|
|
|
|
|
2023-05-28 14:40:10 +00:00
|
|
|
|
/// <inheritdoc />
|
2023-01-04 19:36:38 +00:00
|
|
|
|
public async Task StartAsync(CancellationToken cancellationToken)
|
|
|
|
|
|
{
|
|
|
|
|
|
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
|
|
|
|
|
|
await dbContext.Database.MigrateAsync(cancellationToken);
|
|
|
|
|
|
await dbContext.DisposeAsync();
|
2022-01-04 08:42:12 +00:00
|
|
|
|
}
|
2023-01-04 19:36:38 +00:00
|
|
|
|
|
2023-05-28 14:40:10 +00:00
|
|
|
|
/// <inheritdoc />
|
2023-01-04 19:36:38 +00:00
|
|
|
|
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
2022-01-04 08:42:12 +00:00
|
|
|
|
}
|