我正在为 Core 的 DI 使用 ASP.NET Core、最新的 MediatR 和 MediatR 扩展。
我正在尝试使用官方博客文章建立一个带有验证的管道。例子在这里。
我不明白如何注册/使用该管道类。另一篇博客文章展示了如何做到这一点,但我认为它适用于 AutoFac。
如何为内置容器执行此操作?
我正在为 Core 的 DI 使用 ASP.NET Core、最新的 MediatR 和 MediatR 扩展。
我正在尝试使用官方博客文章建立一个带有验证的管道。例子在这里。
我不明白如何注册/使用该管道类。另一篇博客文章展示了如何做到这一点,但我认为它适用于 AutoFac。
如何为内置容器执行此操作?
您提到的帖子使用 MediatR 2.x。
MediatR 3.0 不久前发布,内置了对流水线的支持。我建议您阅读相关文档。
简而言之,MediatR 现在公开了一个IPipelineBehavior<TRequest, TResponse>,并且您在容器中注册的实例将由 MediatR 在构造处理程序时自动发现。
这是它在 ASP.NET Core 中的样子:
public class MyRequest : IRequest<string>
{
}
public class MyRequestHandler : IRequestHandler<MyRequest, string>
{
public string Handle(MyRequest message)
{
return "Hello!";
}
}
public class TracingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next)
{
Trace.WriteLine("Before");
var response = await next();
Trace.WriteLine("After");
return response;
}
}
非常简单,一个请求、一个处理程序和一个执行一些“记录”的行为。
注册也很简单:
var services = new ServiceCollection();
services.AddMediatR(typeof(Program));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(TracingBehaviour<,>));
var provider = services.BuildServiceProvider();
var mediator = provider.GetRequiredService<IMediator>();
var response = await mediator.Send(new MyRequest());
只需将开放泛型注册TracingBehavior为IPipelineBehavior.