using FabApprovalWorkerService.Models; namespace FabApprovalWorkerService.Services; public class WindowsService : BackgroundService { private readonly ILogger _logger; private readonly IMonInWorkerClient _monInClient; public WindowsService(ILogger logger, IServiceProvider serviceProvider) { _logger = logger ?? throw new ArgumentNullException("ILogger not injected"); using (IServiceScope scope = serviceProvider.CreateScope()) { _monInClient = scope.ServiceProvider.GetService() ?? throw new ArgumentNullException("IMonInWorkerClient not injected"); } } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("Starting Windows service"); try { while (!stoppingToken.IsCancellationRequested) { await Task.Delay(TimeSpan.FromMinutes(5), stoppingToken); _monInClient.PostStatus("WindowsService", StatusValue.Ok); } } catch (OperationCanceledException) { _logger.LogError("The Windows service has been stopped"); _monInClient.PostStatus("WindowsService", StatusValue.Critical); } catch (Exception ex) { _logger.LogError($"An exception occurred when running Windows Service. Exception: {ex.Message}"); _monInClient.PostStatus("WindowsService", StatusValue.Critical); Environment.Exit(1); } } }