79 lines
2.1 KiB
C#
79 lines
2.1 KiB
C#
using System.Collections.Concurrent;
|
|
|
|
namespace YLErp.Events
|
|
{
|
|
/// <summary>
|
|
/// 事件总线
|
|
/// </summary>
|
|
public static class EventBus
|
|
{
|
|
static readonly Easy.MessageHub.IMessageHub _messageHub;
|
|
static readonly ConcurrentDictionary<Guid, string> _dicSubscribe;
|
|
|
|
static EventBus()
|
|
{
|
|
_dicSubscribe = new ConcurrentDictionary<Guid, string>();
|
|
_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);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 发布消息
|
|
/// </summary>
|
|
public static void Publish<T>(T message = null) where T : class
|
|
{
|
|
_messageHub.Publish(message);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 订阅消息
|
|
/// </summary>
|
|
public static Guid Subscribe<T>(Action<T> 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;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 订阅消息
|
|
/// </summary>
|
|
public static void Unsubscribe(Guid token)
|
|
{
|
|
try
|
|
{
|
|
_messageHub.Unsubscribe(token);
|
|
}
|
|
catch { }
|
|
|
|
_dicSubscribe.TryRemove(token, out _);
|
|
}
|
|
}
|
|
}
|