WPF 手撸插件 六 消息总线

 虽然暂时不知道该如何将消息总线集成到插件系统中,但是让我先学习起来吧,本文主要来说说我最近学习的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

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为风而战

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值