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"));
}
相关推荐
bugcome_com15 小时前
零基础入门C#:一篇搞懂核心知识点
c#
程序员敲代码吗19 小时前
如何通过命令行启动COMSOL的参数化、批处理和集群扫描
java·c#·bash
缺点内向20 小时前
C#: 告别繁琐!轻松移除Word文档中的文本与图片水印
c#·自动化·word·.net
喵叔哟21 小时前
06-ASPNETCore-WebAPI开发
服务器·后端·c#
2501_9307077821 小时前
使用 C# .NET 从 PowerPoint 演示文稿中提取背景图片
c#·powerpoint·.net
初级代码游戏1 天前
套路化编程 C# winform 自适应缩放布局
开发语言·c#·winform·自动布局·自动缩放
大空大地20261 天前
流程控制语句--switch多分支语句使用、while循环语句的使用、do...while语句、for循环
c#
kylezhao20191 天前
C#序列化与反序列化详细讲解与应用
c#
JQLvopkk1 天前
C# 实践AI :Visual Studio + VSCode 组合方案
人工智能·c#·visual studio
故事不长丨1 天前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#