DDD事件总线的实现

时间:2024-01-11 22:47:51

基本思路:

(1)       在事件总线内部维护着一个事件与事件处理程序相映射的字典。

(2)       利用反射,事件总线会将实现了IEventHandler的处理程序与相应事件关联到一起,相当于实现了事件处理程序对事件的订阅。

(3)       当发布事件时,事件总线会从字典中找出相应的事件处理程序,然后利用反射去调用事件处理程序中的方法。

核心类(事件总线类)

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection; namespace Framework.EventBus
{
public class EventBus
{ private static EventBus _eventBus = null; private static Dictionary<Type, List<Type>> _eventMapping = new Dictionary<Type, List<Type>>(); // 在这个字典中,key存储的是事件,而value中存储的是事件处理程序 private EventBus() { }
/// <summary>
/// 单例
/// </summary>
/// <returns></returns>
public static EventBus Instance()
{
if (_eventBus == null)
{
_eventBus = new EventBus();
MapEvent2Handler();
}
return _eventBus;
} /// <summary>
/// 发布
/// 这里没有用到队列之类的东西,使用的是直接调用的方式
/// </summary>
/// <param name="eventData"></param>
public void Publish(BaseEvent eventData)
{
// 找出这个事件对应的处理者
Type eventType = eventData.GetType(); if (_eventMapping.ContainsKey(eventType) == true)
{
foreach (Type item in _eventMapping[eventType])
{
MethodInfo mi = item.GetMethod("Handle");
if (mi != null)
{
object o = Activator.CreateInstance(item);
mi.Invoke(o, new object[] { eventData });
}
} }
} /// <summary>
/// 将事件与事件处理程序映射到一起
/// 使用元数据来进行注册
/// </summary>
static void MapEvent2Handler()
{
Assembly assembly = Assembly.GetExecutingAssembly();
Type[] types = assembly.GetTypes(); foreach (Type type in types)
{
Type handlerInterfaceType = type.GetInterface("IEventHandler`1"); // 事件处理者 if (handlerInterfaceType != null) // 若是事件处理者,则以其泛型参数为key,事件处理者的集合为value添加到映射中
{
Type eventType = handlerInterfaceType.GetGenericArguments()[]; // 这里只有一个
// 查找是否存在key
if (_eventMapping.Keys.Contains(eventType))
{
List<Type> handlerTypes = _eventMapping[eventType];
handlerTypes.Add(type);
_eventMapping[eventType] = handlerTypes;
}
else // 存在则添加
{
List<Type> handlerTypes = new List<Type>();
handlerTypes.Add(type);
_eventMapping.Add(eventType, handlerTypes);
}
}
}
} }
}

 

核心类(事件基类)

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Framework.EventBus
{
public class BaseEvent
{ /// <summary>
/// 事件发生的时间
/// </summary>
public DateTime EventTime { get; set; } /// <summary>
/// 事件源
/// </summary>
public object EventSource { get; set; } }
}

核心类(事件处理程序接口)

 namespace Framework.EventBus
{
public interface IEventHandler<T>
where T : BaseEvent
{
void Handle(T eventData);
}
}

使用方法

实现接口IEventHandler<T>

 using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Framework.EventBus
{
/// <summary>
/// 实现了IEventHandler<OrderAddedEvent>接口,就是订阅了OrderAddedEvent事件
/// </summary>
public class OrderAddedEventHandler1 : IEventHandler<OrderAddedEvent>
{
public void Handle(OrderAddedEvent eventData)
{ Console.WriteLine("\r\n");
Console.WriteLine("订单的数据是:" );
Console.WriteLine(" 订单号:" + eventData.Order.OrderId);
Console.WriteLine(" 订单金额:" + eventData.Order.OrderAmount);
Console.WriteLine(" 下单时间:" + eventData.Order.OrderDateTime); }
}
}

注:实现了IEventHandler<OrderAddedEvent>接口,就是订阅了OrderAddedEvent事件

订单类

 public class OrderEntity
{ /// <summary>
/// 订单编号
/// </summary>
public string OrderId { get; set; } /// <summary>
/// 下单日期
/// </summary>
public DateTime OrderDateTime { get; set; } /// <summary>
/// 订单金额
/// </summary>
public decimal OrderAmount { get; set; } }

发布事件

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Framework.EventBus
{
class Program
{
static void Main(string[] args)
{
EventBus bus = EventBus.Instance(); OrderEntity order = new OrderEntity() { OrderId = "", OrderDateTime = DateTime.Now, OrderAmount = };
bus.Publish(new OrderAddedEvent() { EventTime = DateTime.Now, Order = order }); // 发布OrderAddedEvent事件, Console.Read();
} }
}

 运行结果

DDD事件总线的实现

改进

(1)实现基于msmq的事件总线,使得系统能够进行分布式的事件订阅和发布。

下载

示例代码

参考资料

aspnetboilerplate

https://github.com/aspnetboilerplate/aspnetboilerplate

分享一个分布式消息总线,基于.NET Socket Tcp的发布-订阅框架

http://www.cxyclub.cn/n/53667/

Guava - EventBus(事件总线)

http://greengerong.com/blog/2014/11/27/guava-eventbus/

DDD~领域事件与事件总线

http://www.cnblogs.com/lori/p/3476703.html

事件总线 EventBus的设计

http://www.cnblogs.com/MartinChen999/archive/2011/12/21/2294034.html