介绍
MediatR 是一个低野心的库,试图解决一个简单的问题——将进程内消息发送与处理消息解耦。
Asp.Net Core
引用包MediatR.Extensions.Microsoft.DependencyInjection
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddMediatR(typeof(Startup));
}
Request/response
public class Ping : IRequest<string> { }
handler
public class PingHandler : IRequestHandler<Ping, string>
{
public Task<string> Handle(Ping request, CancellationToken cancellationToken)
{
return Task.FromResult("Pong");
}
}
通过mediator
发送消息:
var response = await mediator.Send(new Ping());
Debug.WriteLine(response); // "Pong"
Notifications
public class Ping : INotification { }
handlers
public class Pong1 : INotificationHandler<Ping>
{
public Task Handle(Ping notification, CancellationToken cancellationToken)
{
Debug.WriteLine("Pong 1");
return Task.CompletedTask;
}
}
public class Pong2 : INotificationHandler<Ping>
{
public Task Handle(Ping notification, CancellationToken cancellationToken)
{
Debug.WriteLine("Pong 2");
return Task.CompletedTask;
}
}
Publish
await mediator.Publish(new Ping());
pipeline
在请求前或后执行,await next()
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger) => _logger = logger;
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
_logger.LogInformation("----- Handling command {CommandName} ({@Command})", request.GetGenericTypeName(), request);
var response = await next();
_logger.LogInformation("----- Command {CommandName} handled - response: {@Response}", request.GetGenericTypeName(), response);
return response;
}
}
执行顺序
新添加的是接口 IPipelineBehavior<TRequest, TResponse>
这允许您创建将按照在容器中注册的顺序调用的实现(从 MultiInstanceFactory
委托返回)。