using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using DMS.Infrastructure.Interfaces;
namespace DMS.Infrastructure.Services
{
///
/// 消息传递实现,用于在不同组件之间发送消息
///
public class Messenger : IMessenger
{
private readonly ConcurrentDictionary> _recipients = new ConcurrentDictionary>();
///
/// 发送消息
///
/// 消息类型
/// 要发送的消息
public void Send(T message)
{
var messageType = typeof(T);
if (_recipients.TryGetValue(messageType, out var actions))
{
// 创建副本以避免在迭代时修改集合
var actionsCopy = new List(actions);
foreach (var action in actionsCopy)
{
action.Action?.DynamicInvoke(message);
}
}
}
///
/// 注册消息接收者
///
/// 消息类型
/// 接收者
/// 处理消息的动作
public void Register(object recipient, Action action)
{
var messageType = typeof(T);
var recipientAction = new RecipientAction(recipient, action);
_recipients.AddOrUpdate(
messageType,
_ => new List { recipientAction },
(_, list) =>
{
list.Add(recipientAction);
return list;
});
}
///
/// 取消注册消息接收者
///
/// 接收者
public void Unregister(object recipient)
{
foreach (var kvp in _recipients)
{
kvp.Value.RemoveAll(r => r.Recipient == recipient);
}
}
///
/// 取消注册特定类型消息的接收者
///
/// 消息类型
/// 接收者
public void Unregister(object recipient)
{
var messageType = typeof(T);
if (_recipients.TryGetValue(messageType, out var actions))
{
actions.RemoveAll(r => r.Recipient == recipient);
}
}
///
/// 接收者动作封装类
///
private class RecipientAction
{
public object Recipient { get; }
public Delegate Action { get; }
public RecipientAction(object recipient, Delegate action)
{
Recipient = recipient;
Action = action;
}
}
}
}