using Microsoft.Extensions.Options; namespace ECMJobRunner.WebCron.ProfileWorker; public class ProfileWorker( ILogger Logger, IServiceScopeFactory ScopeFactory, IOptions Options) : BackgroundService { private readonly ProfileWorkerOptions _options = Options.Value; private int _workCount = 0; protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _workCount++; if (Logger.IsEnabled(LogLevel.Information)) { Logger.LogInformation("Worker running {workCount} at: {time}", _workCount, DateTimeOffset.Now); } try { // Create a scope to resolve scoped services (ISQLExecutor used by MediatR pipeline) using var scope = ScopeFactory.CreateScope(); var work = scope.ServiceProvider.GetRequiredService(); await work.ExecuteAsync(stoppingToken); } catch (Exception ex) { Logger.LogError(ex, "An unexpected error occurred in ProfileWorker. Work count: {workCount}", _workCount); } await Task.Delay(_options.IntervalMS, stoppingToken); } } }