dotnet-cqrs/Svrnty.CQRS.Events.PostgreSQL/Migration/MigrationHostedService.cs

47 lines
1.4 KiB
C#

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Svrnty.CQRS.Events.PostgreSQL.Migration;
/// <summary>
/// Hosted service that runs database migrations on application startup.
/// </summary>
internal class MigrationHostedService : IHostedService
{
private readonly DatabaseMigrator _migrator;
private readonly ILogger<MigrationHostedService> _logger;
public MigrationHostedService(
DatabaseMigrator migrator,
ILogger<MigrationHostedService> logger)
{
_migrator = migrator ?? throw new ArgumentNullException(nameof(migrator));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Running database migrations...");
try
{
await _migrator.MigrateAsync(cancellationToken);
_logger.LogInformation("Database migrations completed successfully");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to run database migrations");
throw; // Fail application startup if migrations fail
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
// No cleanup needed
return Task.CompletedTask;
}
}