您的位置:首页 > 其它

幸福框架:发布订阅模式 之 同步订阅、异步订阅和离线订阅

2013-05-21 06:43 483 查看

背景

事件驱动解除了发布者和订阅者之间的耦合,在UI层面,我明经常采用这种编程理念。服务器端最近也开始流行起来了,我也一直小范围的在采用。今天就跟大家分享一下我写的一个小框架。

框架原理

一张图片胜过前言万语。



代码示例

下载地址:http://yunpan.cn/Q5SUcWdiA2mmk

项目结构



关键代码

TestEvent.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.Event;
using Happy.Event.Offline;

namespace Happy.Event.Demo.Simple
{
[TestEventInterceptor1Attibute(1)]
[TestEventInterceptor2Attibute(2)]
[Persistable(3)]
internal sealed class TestEvent : IEvent
{
}
}


Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;

using Happy.Event;
using Happy.Event.Offline;

namespace Happy.Event.Demo.Simple
{
class Program
{
static readonly string _QueueName = "Happy.Event.Demo.Simple";

static void Main(string[] args)
{
InitUnity();

var writeQueue = OfflineEventQueueFactory.CreateMSMQOfflineEventQueue(_QueueName);
EventPublisher.Current.AddService(writeQueue);

EventPublisher.Current.Publish(new TestEvent());

new Thread(() =>
{
var readQueue = OfflineEventQueueFactory.CreateMSMQOfflineEventQueue(_QueueName);
var offlineEventProcessor = new OfflineEventProcessor(readQueue);

offlineEventProcessor.Start();
})
.Start();

Console.ReadLine();
}

static void InitUnity()
{
var container = new UnityContainer();

ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container));

container.RegisterType<ISyncEventSubscriber<TestEvent>, TestSyncEventSubscriber1>("TestSyncEventSubscriber1");
container.RegisterType<ISyncEventSubscriber<TestEvent>, TestSyncEventSubscriber2>("TestSyncEventSubscriber2");
container.RegisterType<IAsyncEventSubscriber<TestEvent>, TestAsyncEventSubscriber1>("TestAsyncEventSubscriber1");
container.RegisterType<IAsyncEventSubscriber<TestEvent>, TestAsyncEventSubscriber2>("TestAsyncEventSubscriber2");
container.RegisterType<IOfflineEventSubscriber<TestEvent>, TestOfflineEventSubscriber1>("TestOfflineEventSubscriber1");
container.RegisterType<IOfflineEventSubscriber<TestEvent>, TestOfflineEventSubscriber2>("TestOfflineEventSubscriber2");
}
}
}


执行结果



备注

基于事件的编程,我在真实项目中有过实战的,这个框架目前还没在项目中使用。研发先行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: