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"));
}
相关推荐
Scout-leaf2 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530143 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools4 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的4 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21884 天前
.NET 本地Db数据库-技术方案选型
windows·c#
lindexi4 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
qq_454245034 天前
基于组件与行为的树状节点系统
数据结构·c#
bugcome_com4 天前
C# 类的基础与进阶概念详解
c#
雪人不是菜鸡4 天前
简单工厂模式
开发语言·算法·c#
铸人4 天前
大数分解的Shor算法-C#
开发语言·算法·c#