| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using TeamAAS.Motion.Models;
- namespace TeamAAS.Motion.AdapterFactorys
- {
- public class DevicePluginManager
- {
- private readonly Dictionary<string, IDeviceAdapterFactory> _factories = new();
- public Dictionary<string, IDeviceAdapterFactory> Factories => _factories;
- public DevicePluginManager()
- {
- // 1. 扫描当前 AppDomain 中所有程序集
- var factoryTypes = AppDomain.CurrentDomain.GetAssemblies()
- .SelectMany(a => a.GetTypes())
- .Where(t => typeof(IDeviceAdapterFactory).IsAssignableFrom(t)
- && !t.IsInterface
- && !t.IsAbstract);
- // 2. 实例化并注册到字典
- foreach ( var type in factoryTypes )
- {
- try
- {
- var factory = (IDeviceAdapterFactory)Activator.CreateInstance(type);
- if ( !_factories.ContainsKey(factory.Key) )
- {
- _factories.Add(factory.Key, factory);
- }
- }
- catch ( Exception ex )
- {
- // 记录日志:实例化失败
- Console.WriteLine($"加载工厂 {type.Name} 失败: {ex.Message}");
- }
- }
- }
- /// <summary>
- /// 根据配置获取工厂,如果找不到则抛出异常或返回默认仿真
- /// </summary>
- public IDeviceAdapterFactory GetFactory(MotionDeviceConfig config)
- {
- if ( Factories.TryGetValue(config.AdapterKey, out var factory) )
- return factory;
- // 健壮性处理:未找到时,回退到仿真模式 或 抛出明确异常
- if ( Factories.TryGetValue("Simulated", out var fallback) )
- {
- Console.WriteLine($"警告:未找到适配器 '{config.AdapterKey}',已切换至仿真模式");
- return fallback;
- }
- throw new NotSupportedException($"未注册的适配器类型: {config.AdapterKey}");
- }
- }
- }
|