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"));
}
相关推荐
FuckPatience1 小时前
C# SqlSugar+SQLite: 无法加载 DLL“e_sqlite3”: 找不到指定的模块
开发语言·c#
HelloRevit1 小时前
Windows Server SMB 共享文件 回收站
windows·c#
曹牧2 小时前
C#:ToDouble
开发语言·c#
yongui478342 小时前
使用C#实现Excel实时读取并导入SQL数据库
数据库·c#·excel
阿蒙Amon3 小时前
C#每日面试题-简述匿名方法
java·面试·c#
波波0073 小时前
C# 中静态类的正确与错误用法
c#
阿蒙Amon3 小时前
C#每日面试题-简述匿名类型
开发语言·c#
jghhh013 小时前
C#中实现不同进程(EXE)间通信的方案
java·单例模式·c#
2501_930707784 小时前
使用C#代码在 Word 中删除页眉或页脚
开发语言·c#·word
警醒与鞭策5 小时前
大模型对比
unity·性能优化·c#·游戏引擎·cursor