虽然暂时不知道该如何将消息总线集成到插件系统中,但是让我先学习起来吧,本文主要来说说我最近学习的Reface.EventBus
Reface.EventBus有两个版本,分别支持.Net Framework和 .Net Core。
我们这里先说支持.Net Framework的版本,先在项目中引入,如下图。
运行效果如下图。
定义一个新事件,代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Reface.EventBus;
namespace EventBusDemo
{
//定义一个新事件
public class ConsoleStarted: Event
{
public ConsoleStarted(object source) : base(source)
{
Console.WriteLine("控制台启动");
}
}
}
定义一个监听上面事件的类,代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Reface.EventBus;
namespace EventBusDemo
{
//创建一个监听事件
public class OnConsoleStarted : IEventListener<ConsoleStarted>
{
public void Handle(ConsoleStarted @event)
{
Console.WriteLine("信息发布者:"+@event.Source+"监听到控制台启动");
foreach (string key in @event.Context.Keys)
{
Console.WriteLine("消息内容关键字:" + key + "---消息内容:" + @event.Context[key].ToString());
}
}
}
}
在Main函数中定义消息并发布消息。代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Reface.EventBus;
namespace EventBusDemo
{
class Program
{
static void Main(string[] args)
{
//创建一个EvenBus的单例
IEventBus eventBus = new DefaultEventBus();
ConsoleStarted consoleStarted = new ConsoleStarted("张三");
consoleStarted.Context.Add("问候语","你好我是张三");
//发布启动控制台的消息
eventBus.Publish(consoleStarted);
Console.ReadLine();
}
}
}
让我们皮一下,如果到 这里你就开始运行项目,那么你会发现你获得了一个NULL,哈哈。这是因为在.Net Framework中需要设置配置文件后才能正常运行,哪个是配置文件?就行项目中的App.config文件。
App.config文件内容如下。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="eventBus" type="Reface.EventBus.Configuration.EventBusSection, Reface.EventBus"/>
</configSections>
<eventBus>
<listeners>
<add type="EventBusDemo.OnConsoleStarted, EventBusDemo" />
</listeners>
</eventBus>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
还不会吗?那我又示例提供呦~!不过需要你的积分,哈哈,欢迎各位大佬下载。
https://download.csdn.net/download/xingchengaiwei/89651412
内容扩展,上面的示例只是让我们快速的开始使用Reface.EventBus,下面根据官网的说明,补充一下。
1、注册监听者的方式
除了通过 config 文件的方法,我们还提供了其它方法来注册监听者。
只要实现了 Reface.EventBus.IEventListenerFinder 并在构造 DefaultEventBus 时作为参数传入,便可以订制的方式注册监听者。 目前自带的注册方式有:
- Reface.EventBus.EventListenerFinders.ConfigurationEventListenerFinder 通过 config 文件来注册
- Reface.EventBus.EventListenerFinders.AssembliesEventListenerFinder 通过注册程序集,并返反射其中的类型来得到所有实现了 Reface.EventBus.IEventListenerFinder 的成员
- Reface.EventBus.EventListenerFinders.DefaultEventListenerFinder 通过编码的方式注册监听者
2、定义监听者的执行顺序。
向 IEventListener 的实现类再添加 IPrioritized 接口,并实现 Priority 属性,便可以指定执行的顺序。
- Priority 的值越小,越先执行
- 未实现 IPrioritized 的 IEventListener 认为 Priority = 0
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » WPF 手撸插件 五 消息总线
发表评论 取消回复