程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> EventBus實現、發布訂閱及XML加載

EventBus實現、發布訂閱及XML加載

編輯:關於.NET

受到CQRS的影響,寫了個EventBus,能實現發布訂閱模式執行event,在DDD模 型中,可以使用如下代碼觸發事件:

EventBus bus = EventBus.Instance();
bus.Publish(new OrderAddedEvent());

解決方案結構圖如下,很簡單易懂:

xml事件配置代碼sample如下(1個event可以定義多個訂閱者,如下):

<?xml version="1.0" encoding="utf-8" ?>
<Events>
  <Event>
    

<PublishEvent>ConsoleApplication2.code.Events.OrderAddedEvent<

/PublishEvent>
    <SubscribedEvents>
      

<SubscribedEvent>ConsoleApplication2.code.EventHandlers.OrderAdde

dEventHandler_CachePrepare</SubscribedEvent>
        

<SubscribedEvent>ConsoleApplication2.code.EventHandlers.OrderAdde

dEventHandler_PDFGenerate</SubscribedEvent>
    </SubscribedEvents>
  </Event>
  <Event>
    

<PublishEvent>ConsoleApplication2.code.Events.OrderDeletedEvent&l

t;/PublishEvent>
    <SubscribedEvents>
      

<SubscribedEvent>ConsoleApplication2.code.EventHandlers.OrderDele

tedEventHandler_NotifyClient</SubscribedEvent>
      

<SubscribedEvent>ConsoleApplication2.code.EventHandlers.OrderDele

tedEventHandler_RemovCache</SubscribedEvent>
    </SubscribedEvents>
  </Event>
</Events>

我們先來定義Event:

public class BaseEvent         //空的,不需要實現其他方法
{
}
public class OrderAddedEvent : BaseEvent      //訂單已經加入,觸發的

event
{
}
public class OrderDeletedEvent : BaseEvent     //訂單已經刪除,觸發的

event
{
        public Guid OrderId { get; set; }
        public OrderDeletedEvent(Guid orderId)
        {
            this.OrderId = orderId;
        }
}

定義事件的處理程序:

public interface IEventHandler<T>
        where T : BaseEvent
{
        void Handle(T evt);
}
public class OrderDeletedEventHandler_NotifyClient : 

IEventHandler<OrderDeletedEvent>
{
        public void Handle(OrderDeletedEvent evt)
        {
            Console.WriteLine("[Order deleted] Notified.");
        }
}

上面2個步驟很簡單,只是簡單的定義事件、事件處理程序,要怎樣才能觸發 事件處理程序並且做成可配置的方式呢?請看下面代碼即可:

private static Dictionary<Type, List<Type>> eventMapping = 

new Dictionary<Type, List<Type>>();
    
XElement root=XElement.Load(System.IO.Path.Combine

(AppDomain.CurrentDomain.BaseDirectory, "EventBus.xml"));  //

這個xml文件需要設置為一直拷貝到程序目錄中
foreach (var evt in root.Elements("Event"))
{
       List<Type> eventHandlers = new List<Type>();
    
       Type publishEventType = Type.GetType(evt.Element("PublishEvent").Value);
       foreach (var subscritedEvt in evt.Elements("SubscribedEvents"))
            foreach (var concreteEvt in subscritedEvt.Elements("SubscribedEvent"))
                eventHandlers.Add(Type.GetType(concreteEvt.Value));
    
       eventMapping[publishEventType] = eventHandlers; //加入Dictionary中
}

再來上發布代碼:

public void Publish(BaseEvent evt)
        {
            var result = from tb in eventMapping
                         where tb.Key.Equals(evt.GetType())
                         select tb;
    
            foreach (KeyValuePair<Type, List<Type>> t in result.ToList())
            {
                foreach (Type tt in t.Value)
                {
                    Type targetType = tt;
                    MethodInfo mi=targetType.GetMethod

("Handle"); //這個Handle文本字符串,必須和

IEventHandler<T>中定義的方法一致
                    if(mi==null)
                        continue;
    
                    object o = Activator.CreateInstance(targetType);  

//new實例
                    mi.Invoke(o, new object[] { evt });               

//調用方法,並且傳入事件參數
                }
            }
        }

運行效果圖如下:

查看本欄目

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved