虽然暂时不知道该如何将消息总线集成到插件系统中,但是让我先学习起来吧,本文主要来说说我最近学习的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.Core.EventBus;
namespace EventBusCoreDemo
{
    //定义一个新事件
    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.Core.EventBus;
namespace EventBusCoreDemo
{
    //创建一个监听事件
    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());
            }
        }
    }
}
 
定义一个全局消息订阅这,代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Reface.Core.EventBus;
namespace EventBusCoreDemo
{
    public class AllListener : IEventListener<Event>
    {
        public void Handle(Event @event)
        {
            Console.WriteLine("事件被触发 : {0}", @event.GetType().Name);
        }
    }
}
 
Main函数,代码如下。
using Microsoft.Extensions.DependencyInjection;
using Reface.Core.EventBus;
namespace EventBusCoreDemo
{
    internal class Program
    {
        static void Main(string[] args)
        {
            ServiceCollection serviceCollection = new ServiceCollection();
            serviceCollection
                .AddEventBus()
                .AddEventListeners(typeof(Program).Assembly);
            IServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
            ConsoleStarted consoleStarted = new ConsoleStarted("张三");
            consoleStarted.Context.Add("问候语", "你好我是张三");
            IEventBus eventBus = serviceProvider.GetService<IEventBus>();
            eventBus.Publish(consoleStarted);
            Console.ReadLine();
        }
    }
}
 
如老样子,提供代码示例,不够我觉得,都这样了再下载代码示例是不是过分了……
https://download.csdn.net/download/xingchengaiwei/89651537



















