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"));
}
相关推荐
大空大地202625 分钟前
流程控制语句--switch多分支语句使用、while循环语句的使用、do...while语句、for循环
c#
kylezhao20192 小时前
C#序列化与反序列化详细讲解与应用
c#
JQLvopkk2 小时前
C# 实践AI :Visual Studio + VSCode 组合方案
人工智能·c#·visual studio
故事不长丨2 小时前
C#线程同步:lock、Monitor、Mutex原理+用法+实战全解析
开发语言·算法·c#
kingwebo'sZone2 小时前
C#使用Aspose.Words把 word转成图片
前端·c#·word
大空大地20263 小时前
表达式与运算符
c#
向上的车轮4 小时前
为什么.NET(C#)转 Java 开发时常常在“吐槽”Java:checked exception
java·c#·.net
心疼你的一切5 小时前
Unity异步编程神器:Unitask库深度解析(功能+实战案例+API全指南)
深度学习·unity·c#·游戏引擎·unitask
.房东的猫16 小时前
ERP(金蝶云星空)开发【安装篇】
c#
fie88891 天前
基于C#的推箱子小游戏实现
开发语言·c#