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 _logger; public BackgroundWorkerStartupService( IServiceProvider serviceProvider, IHostApplicationLifetime applicationLifetime, ILogger 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(); await initializer.RunAsync(); _logger.LogInformation("Background worker startup initialization completed."); } catch (Exception ex) { _logger.LogError(ex, "Background worker initialization failed."); } } }