MediatR 是一个流行的开源库,用于在.NET应用中实现中介者模式(Mediator Pattern)。它通过封装消息的发送与处理逻辑,提供了一种简洁优雅的组件间通信方式。
虽然常与CQRS(命令查询职责分离)架构结合使用,但其应用场景不仅限于此。开发者可通过创建简单的C#命令/查询类及对应的处理程序,利用MediatR将请求分发给相应处理逻辑。此外,MediatR还支持实现通知系统。
本文将以用户注册系统为例,展示如何在ASP.NET Core中利用MediatR的通知功能实现事件驱动的解耦架构。
在用户管理系统中,当新用户注册时,系统需执行以下操作:
传统实现可能导致服务间紧耦合,而MediatR的通知机制可优雅解决此问题。
用户注册时触发INotification
事件:
using MediatR;
public class UserRegisteredNotification : INotification
{
public string UserId { get; }
public string Email { get; }
public UserRegisteredNotification(string userId, string email)
{
UserId = userId;
Email = email;
}
}
各服务独立订阅同一事件。
处理程序1:发送欢迎邮件
public class SendWelcomeEmailHandler : INotificationHandler<UserRegisteredNotification>
{
private readonly ILogger<SendWelcomeEmailHandler> _logger;
public SendWelcomeEmailHandler(ILogger<SendWelcomeEmailHandler> logger)
=> _logger = logger;
public Task Handle(UserRegisteredNotification notification, CancellationToken cancellationToken)
{
_logger.LogInformation($"向 {notification.Email} 发送欢迎邮件");
// 模拟邮件发送逻辑
return Task.CompletedTask;
}
}
处理程序2:记录注册日志
public class LogUserRegistrationHandler : INotificationHandler<UserRegisteredNotification>
{
private readonly ILogger<LogUserRegistrationHandler> _logger;
public LogUserRegistrationHandler(ILogger<LogUserRegistrationHandler> logger)
=> _logger = logger;
public Task Handle(UserRegisteredNotification notification, CancellationToken cancellationToken)
{
_logger.LogInformation($"用户注册:ID {notification.UserId}, 邮箱 {notification.Email}");
return Task.CompletedTask;
}
}
处理程序3:通知分析服务
public class AnalyticsServiceHandler : INotificationHandler<UserRegisteredNotification>
{
private readonly ILogger<AnalyticsServiceHandler> _logger;
public AnalyticsServiceHandler(ILogger<AnalyticsServiceHandler> logger)
=> _logger = logger;
public Task Handle(UserRegisteredNotification notification, CancellationToken cancellationToken)
{
_logger.LogInformation($"分析服务:追踪新用户注册 {notification.UserId}");
return Task.CompletedTask;
}
}
在Program.cs
中注册MediatR并实现用户注册端点:
var builder = WebApplication.CreateBuilder(args);
// 注册MediatR
builder.Services.AddMediatR(Assembly.GetExecutingAssembly());
var app = builder.Build();
// 用户注册的极简API端点
app.MapPost("/register", async (UserRegistrationRequest request, IMediator mediator) =>
{
var userId = Guid.NewGuid().ToString();
// 模拟用户注册(如保存至数据库)
await mediator.Publish(new UserRegisteredNotification(userId, request.Email));
return Results.Ok(new { Message = "用户注册成功!", UserId = userId });
});
app.Run();
// 用户注册请求DTO
public record UserRegistrationRequest(string Email);
✅ 组件解耦:邮件服务、日志服务与分析服务相互独立。
✅ 可扩展性:新增处理程序(如短信通知)无需修改现有代码。
✅ 可测试性:各处理程序可单独测试。
通过MediatR通知机制,您可构建灵活、可扩展且易维护的事件驱动架构,确保各服务仅关注自身职责,互不干扰。