using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Elsa.EntityFrameworkCore.Common;
/// <summary>
/// Executes EF Core migrations using the specified <see cref="DbContext"/> type.
/// </summary>
public class RunMigrationsHostedService<TDbContext> : IHostedService where TDbContext : DbContext
{
private readonly IServiceScopeFactory _scopeFactory;
/// Initializes a new instance of the <see cref="RunMigrationsHostedService{TDbContext}"/> class.
public RunMigrationsHostedService(IServiceScopeFactory scopeFactory)
_scopeFactory = scopeFactory;
}
/// <inheritdoc />
public async Task StartAsync(CancellationToken cancellationToken)
using var scope = _scopeFactory.CreateScope();
var dbContextFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<TDbContext>>();
await using var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
await dbContext.Database.MigrateAsync(cancellationToken);
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;