Apply migrations on startup
This commit is contained in:
@@ -45,6 +45,8 @@ public static class DependencyInjectionExtensions
|
|||||||
|
|
||||||
services.AddHttpContextAccessor();
|
services.AddHttpContextAccessor();
|
||||||
|
|
||||||
|
services.AddHostedService<ApplyMigrationsService>();
|
||||||
|
|
||||||
return services;
|
return services;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
22
src/WebApi/Persistence/ApplyMigrationsService.cs
Normal file
22
src/WebApi/Persistence/ApplyMigrationsService.cs
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Vegasco.WebApi.Persistence;
|
||||||
|
|
||||||
|
public class ApplyMigrationsService : IHostedService
|
||||||
|
{
|
||||||
|
private readonly IServiceScopeFactory _scopeFactory;
|
||||||
|
|
||||||
|
public ApplyMigrationsService(IServiceScopeFactory scopeFactory)
|
||||||
|
{
|
||||||
|
_scopeFactory = scopeFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task StartAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
using IServiceScope scope = _scopeFactory.CreateScope();
|
||||||
|
await using var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||||
|
await dbContext.Database.MigrateAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user