| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using Microsoft.Extensions.DependencyInjection; |
| | | 3 | | using Microsoft.Extensions.Hosting; |
| | | 4 | | |
| | | 5 | | namespace Elsa.Persistence.EFCore; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Executes EF Core migrations using the specified <see cref="DbContext"/> type. |
| | | 9 | | /// </summary> |
| | | 10 | | public class RunMigrationsHostedService<TDbContext> : IHostedService where TDbContext : DbContext |
| | | 11 | | { |
| | | 12 | | private readonly IServiceScopeFactory _scopeFactory; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Initializes a new instance of the <see cref="RunMigrationsHostedService{TDbContext}"/> class. |
| | | 16 | | /// </summary> |
| | 0 | 17 | | public RunMigrationsHostedService(IServiceScopeFactory scopeFactory) |
| | | 18 | | { |
| | 0 | 19 | | _scopeFactory = scopeFactory; |
| | 0 | 20 | | } |
| | | 21 | | |
| | | 22 | | /// <inheritdoc /> |
| | | 23 | | public async Task StartAsync(CancellationToken cancellationToken) |
| | | 24 | | { |
| | 0 | 25 | | using var scope = _scopeFactory.CreateScope(); |
| | 0 | 26 | | var dbContextFactory = scope.ServiceProvider.GetRequiredService<IDbContextFactory<TDbContext>>(); |
| | 0 | 27 | | await using var dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken); |
| | 0 | 28 | | await dbContext.Database.MigrateAsync(cancellationToken); |
| | 0 | 29 | | } |
| | | 30 | | |
| | | 31 | | /// <inheritdoc /> |
| | 0 | 32 | | public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; |
| | | 33 | | } |