C# MediatR 中介者模式 观察者模式

MediatR把参数类型与要执行的类绑定,可以实现一对多发布、订阅。

工控中常用Rx.Net代替,灵活性高。

Microsoft DI 注册

winform要用MediatR 12.0.1版本,之后的版本适用于Asp.Net Core

csharp 复制代码
using Microsoft.Extensions.DependencyInjection;
using MediatR;
using System.Reflection;

namespace Net8Test
{
    internal static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            // To customize application configuration such as set high DPI settings or default font,
            // see https://aka.ms/applicationconfiguration.
            ApplicationConfiguration.Initialize();

            //AppContext.SetSwitch("MediatR.DisableLicenseCheck", true);

            var services = new ServiceCollection();

            // Register SeqLoggerHelper as singleton
            services.AddSingleton(new Helper.SeqLoggerHelper(seqUrl: "http://192.168.202.74:5341/"));

            // Register MediatR and handlers from this assembly
            services.AddMediatR(cfg =>
            {
                cfg.RegisterServicesFromAssembly(typeof(Program).Assembly);
            });

            // Register forms
            services.AddTransient<Form3>();

            var provider = services.BuildServiceProvider();

            // Resolve and run Form3 from DI container using IServiceProvider.GetService
            var form = (Form3)provider.GetService(typeof(Form3))!;
            Application.Run(form);
        }
    }
}

定义Command

csharp 复制代码
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Net8Test.Services.MediatR
{
    public record VisionResultNotification(string ResultJSON) : INotification;
}

Command绑定到类1

csharp 复制代码
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Net8Test.Services.MediatR
{
    public class ArmActionHandler : INotificationHandler<VisionResultNotification>
    {
        public Task Handle(VisionResultNotification notification, CancellationToken cancellationToken)
        {
            Console.WriteLine($"机械臂收到识别结果: {notification.ResultJSON}");
            return Task.CompletedTask;
        }
    }
}

Command绑定到类2

csharp 复制代码
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Net8Test.Services.MediatR
{
    public class LoggerHandler : INotificationHandler<VisionResultNotification>
    {
        public Task Handle(VisionResultNotification notification, CancellationToken cancellationToken)
        {
            Console.WriteLine($"日志记录: {notification.ResultJSON}");
            return Task.CompletedTask;
        }
    }
}

发布

csharp 复制代码
private async void button3_Click(object sender, EventArgs e)
{
    if (_mediator is null)
    {
        UIMessageTip.ShowWarning("Mediator 未注入");
        return;
    }

    await _mediator.Publish(new VisionResultNotification("OK"));
}
相关推荐
海盗12345 小时前
WPF上位机组件开发-设备状态运行图基础版
开发语言·c#·wpf
浮生如梦_6 小时前
C# 窗体工厂类 - 简单工厂模式演示案例
计算机视觉·c#·视觉检测·简单工厂模式
两千次7 小时前
web主从站
windows·c#
lihongli0007 小时前
四连杆机构驱动角与被驱动连杆角度关系
c#
℡枫叶℡7 小时前
C# - 指定友元程序集
开发语言·c#·友元程序集
黑棠会长7 小时前
微服务实战.06 |微服务对话时,你选择打电话还是发邮件?
微服务·云原生·架构·c#
xb11327 小时前
C#串口通信
开发语言·c#
周杰伦fans7 小时前
CAD二次开发中的线程、异步操作与LockDocument
c#
绿浪19849 小时前
C#与C++高效互操作指南
c++·c#
jghhh019 小时前
基于C#的CAN总线BMS上位机开发方案
开发语言·c#