BugFree.MediatR 1.0.2025.1119-beta1105

This is a prerelease version of BugFree.MediatR.
dotnet add package BugFree.MediatR --version 1.0.2025.1119-beta1105
                    
NuGet\Install-Package BugFree.MediatR -Version 1.0.2025.1119-beta1105
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BugFree.MediatR" Version="1.0.2025.1119-beta1105" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BugFree.MediatR" Version="1.0.2025.1119-beta1105" />
                    
Directory.Packages.props
<PackageReference Include="BugFree.MediatR" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BugFree.MediatR --version 1.0.2025.1119-beta1105
                    
#r "nuget: BugFree.MediatR, 1.0.2025.1119-beta1105"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BugFree.MediatR@1.0.2025.1119-beta1105
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BugFree.MediatR&version=1.0.2025.1119-beta1105&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=BugFree.MediatR&version=1.0.2025.1119-beta1105&prerelease
                    
Install as a Cake Tool

BugFree.MediatR 说明

BugFree.MediatR 是一个轻量的通知发布-订阅中介器实现,面向 .NET 平台,包含:

  • Core:BugFree.MediatR(接口与通用 DI 扩展)
  • 内存实现:BugFree.MediatR.Memory
  • Redis 分布式实现:BugFree.MediatR.Redis

适用于本进程解耦的通知分发,或通过 Redis 队列实现跨进程/跨节点的简单分布式通知广播。


功能特性

  • 接口最小化:IMediator、INotification、INotificationHandler<T>
  • DI 一键扫描处理器:services.AddNotificationHandlers(...)
  • 内存版中介器:零外部依赖,低开销,表达式缓存无反射热路径
  • Redis 版中介器:基于 NewLife.Redis 的队列,发布/订阅分离,支持托管后台订阅服务
  • 处理器多实例注册(按泛型闭包接口注册),避免重复注入

目标框架

当前三个项目均为 net8.0。按 BugFree 生态规范,后续将视需要补充多目标框架(netstandard2.0/2.1、net6.0+ 等)同时保持 API 稳定与二进制兼容。


安装与引用

在解决方案中直接引用对应项目,或通过 NuGet(若已发布)引用以下包:

  • BugFree.MediatR
  • BugFree.MediatR.Memory
  • BugFree.MediatR.Redis

Redis 版依赖:NewLife.Redis


核心接口

public interface INotification { }

public interface INotificationHandler<in TNotification> where TNotification : INotification
{
	ValueTask Handle(TNotification notification, CancellationToken cancellationToken);
}

public interface IMediator
{
	Task Publish(INotification notification, CancellationToken cancellationToken = default);
}

扫描并注册处理器

BugFree.MediatR 提供 AddNotificationHandlers 扩展,可批量扫描并按接口闭包 INotificationHandler<T> 注册处理器(默认 Singleton 生命周期):

// 扫描当前 AppDomain 已加载程序集(默认)
services.AddNotificationHandlers();

// 或指定过滤器(仅包含以 BugFree. 开头的程序集)
services.AddNotificationHandlers(true, asm => asm.GetName().Name!.StartsWith("BugFree."));

// 或显式传入要扫描的程序集
services.AddNotificationHandlers(false, null, typeof(Program).Assembly);

内存版与 Redis 版注册扩展会自动调用该扫描逻辑。


内存中介器(BugFree.MediatR.Memory)

内存实现适用于单进程内的通知分发,零外部依赖,使用表达式树缓存委托,避免反射/动态开销。

注册:

services.AddMemoryMediator();

定义通知与处理器:

public sealed class UserCreated : INotification
{
	public string? Id { get; set; }
}

public sealed class UserCreatedHandler : INotificationHandler<UserCreated>
{
	public ValueTask Handle(UserCreated notification, CancellationToken cancellationToken)
	{
		Console.WriteLine($"UserCreated: {notification.Id}");
		return ValueTask.CompletedTask;
	}
}

发布通知:

var sp = new ServiceCollection()
	.AddMemoryMediator()
	.BuildServiceProvider();

var mediator = sp.GetRequiredService<IMediator>();
await mediator.Publish(new UserCreated { Id = "42" });

注意:MemoryMediator 当前通过 GetService(INotificationHandler<T>) 获取单个处理器并调用,若注册了多个同类型处理器,将调用第一个可解析的处理器。


Redis 中介器(BugFree.MediatR.Redis)

Redis 版将发布与消费解耦:

  • 发布:IMediator.Publish 将通知序列化为 JSON 并写入 Redis 队列
  • 订阅:后台托管服务批量从队列取出,反序列化并依次调用所有匹配处理器

注册(仅发布,不自动订阅):

services.AddRedisMediator(o =>
{
	o.Configuration = "server=192.168.31.200:6379;password=Ace12345678!;db=0;timeout=3000";   // 典型配置,亦可设置 Password/Db 等
	o.QueueName = "bugfree.mediatr.notify"; // 可选,默认同名
	o.BatchSize = 10;               // 可选
	o.IdleDelay = 1000;             // 可选(毫秒)
});

注册后台订阅服务(消费与分发到处理器):

builder.Services.AddRedisMediatorWorker(o =>
{
	o.Configuration = "server=192.168.31.200:6379;password=Ace12345678!;db=0;timeout=3000";
	o.QueueName = "bugfree.mediatr.notify";
});

典型主机构建示例:

var builder = Host.CreateDefaultBuilder(args)
	.ConfigureServices(services =>
	{
		services.AddNotificationHandlers(); // 可省略,Redis 扩展内部会调用
		services.AddRedisMediator(o => o.Configuration = "server=192.168.31.200:6379;password=Ace12345678!;db=0;timeout=3000");
		services.AddRedisMediatorWorker(o => o.Configuration = "server=192.168.31.200:6379;password=Ace12345678!;db=0;timeout=3000");
	});

await builder.Build().RunAsync();

选项说明(RedisMediatorOptions):

  • QueueName:队列名,默认 bugfree.mediatr.notify
  • IdleDelay:空闲等待(毫秒),默认 1000

性能与实现要点

  • 处理器调用使用表达式树编译的委托并做类型闭包缓存(ConcurrentDictionary<Type, Func<...>>)
  • 内存版同步完成路径直接返回已完成任务,减少分配
  • Redis 订阅使用批量 TakeOneAsync 与轻量异常回退,避免热循环阻塞

最佳实践

  • 为每个通知定义单一职责的 INotificationHandler<T>;Redis 订阅端会按序广播给所有同类型处理器
  • 仅在确有跨进程广播需求时使用 Redis 版;纯进程内推荐内存版以获得最低延迟
  • 使用 AddNotificationHandlers(predicate: ...) 约束扫描范围,减少启动扫描开销

构建

在仓库根目录:

dotnet build BugFree.sln

许可

默认遵循仓库 MIT 许可。

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on BugFree.MediatR:

Package Downloads
BugFree.MediatR.Redis

Package Description

BugFree.MediatR.Memory

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.2025.1119-beta1105 447 11/19/2025