Created
May 15, 2019 12:11
-
-
Save Grinderofl/a2ce16cd064bd2a1ad88216b6534027c to your computer and use it in GitHub Desktop.
Initialize Database from middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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