using Cowain.Base.Helpers; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Plugin.Cowain.Wcs.IServices; using Plugin.Cowain.Wcs.ViewModels; namespace Plugin.Cowain.Wcs.Services; public class WcsStartUpHostedService : IHostedService { private IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; public WcsStartUpHostedService(IServiceScopeFactory scopeFactory, ILogger logger) { _scopeFactory = scopeFactory; _logger = logger; } public async Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("WcsStartUpHostedService Start"); try { await FindTaskAsync(); using var scope = _scopeFactory.CreateScope(); var taskHandlers = scope.ServiceProvider.GetRequiredService>(); var stationQueueHostedService = taskHandlers.OfType().FirstOrDefault(); if (stationQueueHostedService == null) { return; } stationQueueHostedService.FindTaskAction = async (StationViewModel item) => { await FindTaskAsync(); }; } catch (Exception ex) { _logger.LogError(ex, "WcsStartUpHostedService Start Error"); return; } _logger.LogInformation("WcsStartUpHostedService Started"); } private async Task FindTaskAsync() { try { using var scope = _scopeFactory.CreateScope(); var wcsParamService = scope.ServiceProvider.GetRequiredService(); // 使用WcsParamService的缓存功能获取参数 var findTaskEnableResult = await wcsParamService.GetParamAsync("FindTaskEnable"); if (findTaskEnableResult.IsSuccess) { if (bool.TryParse(findTaskEnableResult.Data!.Param, out bool findTaskEnable) && findTaskEnable) { var findFlowTaskService = scope.ServiceProvider.GetRequiredService(); await findFlowTaskService.FindTaskAsync(); } else { _logger.LogInformation("任务查找功能已禁用"); } } else { _logger.LogInformation($"获取FindTaskEnable参数失败: {findTaskEnableResult.ErrorMessage}"); } } catch (Exception ex) { _logger.LogError(ex, "FindTaskAsync 执行失败"); } } public Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("StationQueueHostedService Stop"); _logger.LogInformation("StationQueueHostedService Stoped"); return Task.CompletedTask; } }