sozsoft-platform/api/src/Sozsoft.Platform.HttpApi.Host/BackgroundWorkerStartupService.cs

59 lines
1.8 KiB
C#
Raw Normal View History

2026-06-13 21:26:19 +00:00
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Sozsoft.Platform;
public class BackgroundWorkerStartupService : IHostedService
{
private readonly IServiceProvider _serviceProvider;
private readonly IHostApplicationLifetime _applicationLifetime;
private readonly ILogger<BackgroundWorkerStartupService> _logger;
public BackgroundWorkerStartupService(
IServiceProvider serviceProvider,
IHostApplicationLifetime applicationLifetime,
ILogger<BackgroundWorkerStartupService> logger)
{
_serviceProvider = serviceProvider;
_applicationLifetime = applicationLifetime;
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_applicationLifetime.ApplicationStarted.Register(() =>
{
_ = Task.Run(InitializeBackgroundWorkersAsync);
});
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
private async Task InitializeBackgroundWorkersAsync()
{
try
{
_logger.LogInformation("Background worker startup initialization started.");
using var scope = _serviceProvider.CreateScope();
var initializer = scope.ServiceProvider.GetRequiredService<BackgroundWorkerInitializer>();
await initializer.RunAsync();
_logger.LogInformation("Background worker startup initialization completed.");
}
catch (Exception ex)
{
_logger.LogError(ex, "Background worker initialization failed.");
}
}
}