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"));
}