背景
事件驱动解除了发布者和订阅者之间的耦合,在UI层面,我明经常采用这种编程理念。服务器端最近也开始流行起来了,我也一直小范围的在采用。今天就跟大家分享一下我写的一个小框架。
框架原理
一张图片胜过前言万语。
代码示例
下载地址:。
项目结构
关键代码
TestEvent.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 using Happy.Event; 8 using Happy.Event.Offline; 9 10 namespace Happy.Event.Demo.Simple11 {12 [TestEventInterceptor1Attibute(1)]13 [TestEventInterceptor2Attibute(2)]14 [Persistable(3)]15 internal sealed class TestEvent : IEvent16 {17 }18 }
Program.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Threading; 7 8 using Microsoft.Practices.ServiceLocation; 9 using Microsoft.Practices.Unity;10 11 using Happy.Event;12 using Happy.Event.Offline;13 14 namespace Happy.Event.Demo.Simple15 {16 class Program17 {18 static readonly string _QueueName = "Happy.Event.Demo.Simple";19 20 static void Main(string[] args)21 {22 InitUnity();23 24 var writeQueue = OfflineEventQueueFactory.CreateMSMQOfflineEventQueue(_QueueName);25 EventPublisher.Current.AddService(writeQueue);26 27 EventPublisher.Current.Publish(new TestEvent());28 29 new Thread(() =>30 {31 var readQueue = OfflineEventQueueFactory.CreateMSMQOfflineEventQueue(_QueueName);32 var offlineEventProcessor = new OfflineEventProcessor(readQueue);33 34 offlineEventProcessor.Start();35 })36 .Start();37 38 Console.ReadLine();39 }40 41 static void InitUnity()42 {43 var container = new UnityContainer();44 45 ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));46 47 container.RegisterType, TestSyncEventSubscriber1>("TestSyncEventSubscriber1");48 container.RegisterType , TestSyncEventSubscriber2>("TestSyncEventSubscriber2");49 container.RegisterType , TestAsyncEventSubscriber1>("TestAsyncEventSubscriber1");50 container.RegisterType , TestAsyncEventSubscriber2>("TestAsyncEventSubscriber2");51 container.RegisterType , TestOfflineEventSubscriber1>("TestOfflineEventSubscriber1");52 container.RegisterType , TestOfflineEventSubscriber2>("TestOfflineEventSubscriber2");53 }54 }55 }
执行结果
备注
基于事件的编程,我在真实项目中有过实战的,这个框架目前还没在项目中使用。研发先行。