using Prism.Ioc; using System; using System.Threading.Tasks; using XP.Hardware.Plc.Abstractions; using XP.Hardware.Plc.Core; using XP.Hardware.Plc.Services; using XP.Hardware.PLC.Configs; namespace XP.Hardware.PLC.Extensions { /// /// PLC 服务扩展方法类 | PLC service extension methods class /// public static class PlcServiceExtensions { /// /// 注册 PLC 服务到容器 | Register PLC services to container /// /// 容器注册器 | Container registry /// 容器注册器,支持链式调用 | Container registry, supports method chaining /// 当 containerRegistry 为 null 时抛出 | Thrown when containerRegistry is null public static IContainerRegistry RegisterPlcServices(this IContainerRegistry containerRegistry) { if (containerRegistry == null) { throw new ArgumentNullException(nameof(containerRegistry), "容器注册器不能为空 | Container registry cannot be null"); } // 注册 PLC 客户端接口和实现类(瞬态)| Register PLC client interface and implementation (transient) containerRegistry.Register(); // 注册 PLC 服务为单例 | Register PLC service as singleton containerRegistry.RegisterSingleton(); // 注册配置加载器(瞬态)| Register configuration loader (transient) containerRegistry.Register(); return containerRegistry; } /// /// 初始化 PLC 服务 | Initialize PLC service /// /// 容器提供者 | Container provider /// PLC 配置 | PLC configuration /// 初始化是否成功 | Whether initialization succeeded /// 当 containerProvider 或 config 为 null 时抛出 | Thrown when containerProvider or config is null public static async Task InitializePlcServiceAsync( this IContainerProvider containerProvider, PlcConfig config) { if (containerProvider == null) { throw new ArgumentNullException(nameof(containerProvider), "容器提供者不能为空 | Container provider cannot be null"); } if (config == null) { throw new ArgumentNullException(nameof(config), "PLC 配置不能为空 | PLC configuration cannot be null"); } // 从容器解析 PlcService 实例 | Resolve PlcService instance from container var plcService = containerProvider.Resolve(); // 调用 InitializeAsync 方法并返回结果 | Call InitializeAsync method and return result return await plcService.InitializeAsync(config); } /// /// 获取 PLC 服务实例 | Get PLC service instance /// /// 容器提供者 | Container provider /// PLC 服务单例实例 | PLC service singleton instance /// 当 containerProvider 为 null 时抛出 | Thrown when containerProvider is null public static PlcService GetPlcService(this IContainerProvider containerProvider) { if (containerProvider == null) { throw new ArgumentNullException(nameof(containerProvider), "容器提供者不能为空 | Container provider cannot be null"); } // 从容器解析并返回 PlcService 单例实例 | Resolve and return PlcService singleton instance from container return containerProvider.Resolve(); } } }