Files
scadaproj/ZB.MOM.WW.Auth/src/ZB.MOM.WW.Auth.ApiKeys/DependencyInjection/ApiKeyMigrationHostedService.cs
T

30 lines
1.1 KiB
C#

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
namespace ZB.MOM.WW.Auth.ApiKeys.DependencyInjection;
/// <summary>
/// Runs the registered <see cref="IApiKeyStoreMigrator"/> at application startup when
/// <see cref="ApiKeyOptions.RunMigrationsOnStartup"/> is <see langword="true"/>. The migrator
/// registered in DI is whichever store provider's implementation won the <c>TryAdd</c> race —
/// SQLite by default, or a provider package (e.g. SQL Server) registered before
/// <c>AddZbApiKeyAuth</c>. The migration is idempotent, so repeated restarts are safe.
/// </summary>
internal sealed class ApiKeyMigrationHostedService(
IApiKeyStoreMigrator migrator,
IOptions<ApiKeyOptions> options) : IHostedService
{
/// <inheritdoc />
public async Task StartAsync(CancellationToken cancellationToken)
{
if (options.Value.RunMigrationsOnStartup)
{
await migrator.MigrateAsync(cancellationToken).ConfigureAwait(false);
}
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}