ActorMessageDispatherComponent.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 void Handle(Session session, object message)
  56. {
  57. if (!this.handlers.TryGetValue(message.GetType(), out IMActorHandler handler))
  58. {
  59. Log.Error($"not found message handler: {message.GetType()}");
  60. return;
  61. }
  62. Entity entity = this.GetComponent<ActorManagerComponent>().Get(((AActorMessage)message).Id);
  63. handler.Handle(session, entity, message);
  64. }
  65. public override void Dispose()
  66. {
  67. if (this.Id == 0)
  68. {
  69. return;
  70. }
  71. base.Dispose();
  72. }
  73. }
  74. }