1
0

Adding WaitAvailable to EFCore extensions

This commit is contained in:
2022-03-23 20:50:20 +01:00
parent e89e8bc69a
commit e38864b32b
4 changed files with 79 additions and 7 deletions

View File

@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
@@ -28,18 +29,24 @@ namespace Microsoft.EntityFrameworkCore
if (database == null)
throw new ArgumentNullException(nameof(database));
var options = new DatabaseMigrationOptions();
optionsAction?.Invoke(options);
if (database.GetProviderType() == DatabaseProvider.InMemory)
return true;
var options = new DatabaseMigrationOptions();
optionsAction?.Invoke(options);
if (string.IsNullOrWhiteSpace(options.MigrationsTableName))
throw new ArgumentNullException(nameof(options.MigrationsTableName), $"The property {nameof(options.MigrationsTableName)} of the {nameof(options)} parameter is required.");
if (string.IsNullOrWhiteSpace(options.Path))
throw new ArgumentNullException(nameof(options.Path), $"The property {nameof(options.Path)} of the {nameof(options)} parameter is required.");
await database.WaitAvailableAsync(opts =>
{
opts.WaitDelay = options.WaitDelay;
opts.Logger = options.Logger;
}, cancellationToken);
var connection = database.GetDbConnection();
try
{
@@ -52,7 +59,58 @@ namespace Microsoft.EntityFrameworkCore
}
finally
{
connection.Close();
await connection.CloseAsync();
}
}
/// <summary>
/// Waits until the database connection is available.
/// </summary>
/// <param name="database">The database connection.</param>
/// <param name="optionsAction">An action to set additional options.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>An awaitable task to wait until the database is available.</returns>
public static async Task WaitAvailableAsync(this DatabaseFacade database, Action<DatabaseMigrationOptions> optionsAction = null, CancellationToken cancellationToken = default)
{
if (database == null)
throw new ArgumentNullException(nameof(database));
if (database.GetProviderType() == DatabaseProvider.InMemory)
return;
var options = new DatabaseMigrationOptions();
optionsAction?.Invoke(options);
options.Logger?.LogInformation("Waiting for a database connection");
var connection = database.GetDbConnection();
while (!cancellationToken.IsCancellationRequested)
{
try
{
await connection.OpenAsync(cancellationToken);
options.Logger?.LogInformation("Database connection available");
return;
}
catch
{
// keep things quiet
try
{
await Task.Delay(options.WaitDelay, cancellationToken);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
return;
}
catch
{
// keep things quiet
}
}
finally
{
await connection.CloseAsync();
}
}
}