using System.Collections.Concurrent; namespace YLErp.Events { /// /// 事件总线 /// public static class EventBus { static readonly Easy.MessageHub.IMessageHub _messageHub; static readonly ConcurrentDictionary _dicSubscribe; static EventBus() { _dicSubscribe = new ConcurrentDictionary(); _messageHub = new Easy.MessageHub.MessageHub(); _messageHub.RegisterGlobalErrorHandler(HandleError); } //处理事件错误 private static void HandleError(Guid guid, Exception ex) { if (ex != null) { _dicSubscribe.TryGetValue(guid, out var eventName); LogFactory.GetLogger(eventName ?? "事件处理").Error(ex); } } /// /// 发布消息 /// public static void Publish(T message = null) where T : class { _messageHub.Publish(message); } /// /// 订阅消息 /// public static Guid Subscribe(Action action) { var guid = _messageHub.Subscribe(action); var type = typeof(T); var attrs = type.GetCustomAttributes(typeof(EventDescriptionAttribute), false); string eventName; if (attrs != null && attrs.Length > 0) { var attr = (EventDescriptionAttribute)attrs[0]; eventName = $"<{type.Name}-{attr.Description}>"; } else { eventName = $"<{type.Name}>"; } _dicSubscribe[guid] = eventName; return guid; } /// /// 订阅消息 /// public static void Unsubscribe(Guid token) { try { _messageHub.Unsubscribe(token); } catch { } _dicSubscribe.TryRemove(token, out _); } } }