DevicePluginManager.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using TeamAAS.Motion.Models;
  7. namespace TeamAAS.Motion.AdapterFactorys
  8. {
  9. public class DevicePluginManager
  10. {
  11. private readonly Dictionary<string, IDeviceAdapterFactory> _factories = new();
  12. public Dictionary<string, IDeviceAdapterFactory> Factories => _factories;
  13. public DevicePluginManager()
  14. {
  15. // 1. 扫描当前 AppDomain 中所有程序集
  16. var factoryTypes = AppDomain.CurrentDomain.GetAssemblies()
  17. .SelectMany(a => a.GetTypes())
  18. .Where(t => typeof(IDeviceAdapterFactory).IsAssignableFrom(t)
  19. && !t.IsInterface
  20. && !t.IsAbstract);
  21. // 2. 实例化并注册到字典
  22. foreach ( var type in factoryTypes )
  23. {
  24. try
  25. {
  26. var factory = (IDeviceAdapterFactory)Activator.CreateInstance(type);
  27. if ( !_factories.ContainsKey(factory.Key) )
  28. {
  29. _factories.Add(factory.Key, factory);
  30. }
  31. }
  32. catch ( Exception ex )
  33. {
  34. // 记录日志:实例化失败
  35. Console.WriteLine($"加载工厂 {type.Name} 失败: {ex.Message}");
  36. }
  37. }
  38. }
  39. /// <summary>
  40. /// 根据配置获取工厂,如果找不到则抛出异常或返回默认仿真
  41. /// </summary>
  42. public IDeviceAdapterFactory GetFactory(MotionDeviceConfig config)
  43. {
  44. if ( Factories.TryGetValue(config.AdapterKey, out var factory) )
  45. return factory;
  46. // 健壮性处理:未找到时,回退到仿真模式 或 抛出明确异常
  47. if ( Factories.TryGetValue("Simulated", out var fallback) )
  48. {
  49. Console.WriteLine($"警告:未找到适配器 '{config.AdapterKey}',已切换至仿真模式");
  50. return fallback;
  51. }
  52. throw new NotSupportedException($"未注册的适配器类型: {config.AdapterKey}");
  53. }
  54. }
  55. }