Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Grinderofl/a2ce16cd064bd2a1ad88216b6534027c to your computer and use it in GitHub Desktop.
Save Grinderofl/a2ce16cd064bd2a1ad88216b6534027c to your computer and use it in GitHub Desktop.
Initialize Database from middleware
public abstract class AbstractAsyncInitializationMiddleware
{
private readonly RequestDelegate next;
private readonly ILogger logger;
private Task initializationTask;
// ReSharper disable AccessToModifiedClosure
protected AbstractAsyncInitializationMiddleware(RequestDelegate next, IApplicationLifetime lifetime, ILogger logger)
{
this.next = next;
this.logger = logger;
var startRegistration = default(CancellationTokenRegistration);
startRegistration = lifetime.ApplicationStarted.Register(() =>
{
initializationTask = InitializeAsync(lifetime.ApplicationStopping);
startRegistration.Dispose();
});
}
protected abstract Task InitializeAsync(CancellationToken cancellationToken);
[UsedImplicitly]
public async Task Invoke(HttpContext context)
{
var task = initializationTask;
if (task != null)
{
await task;
initializationTask = null;
}
await next(context);
}
}
// ReSharper disable SuggestBaseTypeForParameter
public class DatabaseInitializationMiddleware : AbstractAsyncInitializationMiddleware
{
private readonly IdentityContext identityContext;
private readonly DataContext dbContext;
public DatabaseInitializationMiddleware(
RequestDelegate next,
IApplicationLifetime lifetime,
ILogger<DatabaseInitializationMiddleware> logger,
IdentityContext identityContext,
DataContext dbContext) : base(next, lifetime, logger)
{
this.identityContext = identityContext;
this.dbContext = dbContext;
}
protected override async Task InitializeAsync(CancellationToken cancellationToken)
{
if (OperatingEnvironment.IsWindows())
{
await identityContext.Database.MigrateAsync(cancellationToken);
await dbContext.Database.MigrateAsync(cancellationToken);
}
else
{
await identityContext.Database.EnsureCreatedAsync(cancellationToken);
await dbContext.Database.EnsureCreatedAsync(cancellationToken);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment