using System; using System.Collections.Generic; using System.Linq; namespace DDD { public static class EventBus { private static readonly Dictionary> HandlerDictionary = new(); public static void Register(IEventHandler handler) where T : IEvent { var type = typeof(T); if (!HandlerDictionary.ContainsKey(type)) { HandlerDictionary[type] = new List(); } HandlerDictionary[type].Add(handler); } public static void Unregister(IEventHandler handler) where T : IEvent { var type = typeof(T); if (HandlerDictionary.TryGetValue(type, out var list)) { list.Remove(handler); if (list.Count == 0) { HandlerDictionary.Remove(type); } } } public static void Publish(T evt) where T : IEvent { var type = typeof(T); if (HandlerDictionary.TryGetValue(type, out var list)) { foreach (var handler in list.Cast>()) { handler.Handle(evt); } } } public static void ClearAll() { HandlerDictionary.Clear(); } } }