elsa-core/src/modules/Elsa.Persistence.EFCore.Common/RunMigrationsHostedService.cs
Sipke Schoorstra ff1f0833ad
Restore EF Core persistence layer (#6931)
* Restore EF Core persistence layer

Originally, we had moved EF Core to the extensions repo, but in practice this turned out to be rather impractical when debugging elsa-core, given that we would lose all of the state (workflow definitions, instances, etc.) across application restarts.

* Integrate PostgreSQL support into EF Core persistence and enhance BlobStorage workflows provider setup.
2025-09-27 20:39:18 +02:00

33 lines
1.2 KiB
C#

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace Elsa.Persistence.EFCore;
/// <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;
/// <summary>
/// Initializes a new instance of the <see cref="RunMigrationsHostedService{TDbContext}"/> class.
/// </summary>
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);
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}