您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

60 行
1.9 KiB

  1. using JT808.Protocol.Attributes;
  2. using JT808.Protocol.Enums;
  3. using JT808.Protocol.Exceptions;
  4. using JT808.Protocol.Formatters;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Reflection;
  9. using System.Text;
  10. namespace JT808.Protocol.Internal
  11. {
  12. internal class JT808FormatterFactory : IJT808FormatterFactory
  13. {
  14. public Dictionary<Guid, object> FormatterDict { get; }
  15. public JT808FormatterFactory()
  16. {
  17. FormatterDict = new Dictionary<Guid, object>();
  18. Init(Assembly.GetExecutingAssembly());
  19. }
  20. private void Init(Assembly assembly)
  21. {
  22. foreach(var type in assembly.GetTypes().Where(w=>w.GetInterfaces().Contains(typeof(IJT808Formatter))))
  23. {
  24. var implTypes = type.GetInterfaces();
  25. if(implTypes!=null && implTypes .Length>1)
  26. {
  27. var firstType = implTypes.FirstOrDefault(f=>f.Name== typeof(IJT808MessagePackFormatter<>).Name);
  28. var genericImplType = firstType.GetGenericArguments().FirstOrDefault();
  29. if (genericImplType != null)
  30. {
  31. if (!FormatterDict.ContainsKey(genericImplType.GUID))
  32. {
  33. FormatterDict.Add(genericImplType.GUID, Activator.CreateInstance(genericImplType));
  34. }
  35. }
  36. }
  37. }
  38. }
  39. public IJT808FormatterFactory SetMap<TJT808Bodies>()
  40. where TJT808Bodies:JT808Bodies
  41. {
  42. Type type = typeof(TJT808Bodies);
  43. if (!FormatterDict.ContainsKey(type.GUID))
  44. {
  45. FormatterDict.Add(type.GUID, Activator.CreateInstance(type));
  46. }
  47. return this;
  48. }
  49. public void Register(Assembly externalAssembly)
  50. {
  51. Init(externalAssembly);
  52. }
  53. }
  54. }