elsa-core/src/modules/Elsa.EntityFrameworkCore.Common/RunMigrationsHostedService.cs

28 lines
1.1 KiB
C#
Raw Normal View History

2022-01-04 08:42:12 +00:00
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
namespace Elsa.EntityFrameworkCore.Common;
2022-01-04 08:42:12 +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>
public RunMigrationsHostedService(IDbContextFactory<TDbContext> dbContextFactoryFactory) => _dbContextFactory = dbContextFactoryFactory;
2022-01-04 08:42:12 +00:00
2023-05-28 14:40:10 +00:00
/// <inheritdoc />
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-05-28 14:40:10 +00:00
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
2022-01-04 08:42:12 +00:00
}