Files
git.stella-ops.org/src/Notifier/StellaOps.Notifier/StellaOps.Notifier.WebService/Setup/MongoInitializationHostedService.cs
2025-10-28 15:10:40 +02:00

61 lines
2.3 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace StellaOps.Notifier.WebService.Setup;
internal sealed class MongoInitializationHostedService : IHostedService
{
private const string InitializerTypeName = "StellaOps.Notify.Storage.Mongo.Internal.NotifyMongoInitializer, StellaOps.Notify.Storage.Mongo";
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<MongoInitializationHostedService> _logger;
public MongoInitializationHostedService(IServiceProvider serviceProvider, ILogger<MongoInitializationHostedService> logger)
{
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task StartAsync(CancellationToken cancellationToken)
{
var initializerType = Type.GetType(InitializerTypeName, throwOnError: false, ignoreCase: false);
if (initializerType is null)
{
_logger.LogWarning("Notify Mongo initializer type {TypeName} was not found; skipping migration run.", InitializerTypeName);
return;
}
using var scope = _serviceProvider.CreateScope();
var initializer = scope.ServiceProvider.GetService(initializerType);
if (initializer is null)
{
_logger.LogWarning("Notify Mongo initializer could not be resolved from the service provider.");
return;
}
var method = initializerType.GetMethod("EnsureIndexesAsync");
if (method is null)
{
_logger.LogWarning("Notify Mongo initializer does not expose EnsureIndexesAsync; skipping migration run.");
return;
}
try
{
var task = method.Invoke(initializer, new object?[] { cancellationToken }) as Task;
if (task is not null)
{
await task.ConfigureAwait(false);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to run Notify Mongo migrations.");
throw;
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}