ActorMessageDispatherComponent.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Model
  4. {
  5. [ObjectEvent]
  6. public class ActorMessageDispatherComponentEvent : ObjectEvent<ActorMessageDispatherComponent>, IAwake<AppType>, ILoad
  7. {
  8. public void Awake(AppType appType)
  9. {
  10. this.Get().Awake(appType);
  11. }
  12. public void Load()
  13. {
  14. this.Get().Load();
  15. }
  16. }
  17. /// <summary>
  18. /// Actor消息分发组件
  19. /// </summary>
  20. public class ActorMessageDispatherComponent : Component
  21. {
  22. private AppType AppType;
  23. private Dictionary<Type, IMActorHandler> handlers;
  24. public void Awake(AppType appType)
  25. {
  26. this.AppType = appType;
  27. this.Load();
  28. }
  29. public void Load()
  30. {
  31. this.handlers = new Dictionary<Type, IMActorHandler>();
  32. Type[] types = DllHelper.GetMonoTypes();
  33. foreach (Type type in types)
  34. {
  35. object[] attrs = type.GetCustomAttributes(typeof(ActorMessageHandlerAttribute), false);
  36. if (attrs.Length == 0)
  37. {
  38. continue;
  39. }
  40. ActorMessageHandlerAttribute messageHandlerAttribute = (ActorMessageHandlerAttribute)attrs[0];
  41. if (!messageHandlerAttribute.Type.Is(this.AppType))
  42. {
  43. continue;
  44. }
  45. object obj = Activator.CreateInstance(type);
  46. IMActorHandler imHandler = obj as IMActorHandler;
  47. if (imHandler == null)
  48. {
  49. throw new Exception($"message handler not inherit AMEvent or AMRpcEvent abstract class: {obj.GetType().FullName}");
  50. }
  51. Type messageType = imHandler.GetMessageType();
  52. handlers.Add(messageType, imHandler);
  53. }
  54. }
  55. public IMActorHandler GetActorHandler(Type type)
  56. {
  57. this.handlers.TryGetValue(type, out IMActorHandler actorHandler);
  58. return actorHandler;
  59. }
  60. public void Handle(Session session, Entity entity, IActorMessage message)
  61. {
  62. if (!this.handlers.TryGetValue(message.GetType(), out IMActorHandler handler))
  63. {
  64. Log.Error($"not found message handler: {message.GetType().FullName}");
  65. return;
  66. }
  67. handler.Handle(session, entity, message);
  68. }
  69. public override void Dispose()
  70. {
  71. if (this.Id == 0)
  72. {
  73. return;
  74. }
  75. base.Dispose();
  76. }
  77. }
  78. }