如何注册 MediatR post 处理器

How do I register a MediatR post processor

我想尝试 MediatR 中的新管道功能:https://github.com/jbogard/MediatR/wiki/Behaviors

我尝试了以下方法,但没有执行

services.AddMediatR();                    
services.AddTransient(typeof(IRequestPostProcessor<,>), typeof(PostHandler<,>));

我错过了什么?

您需要注册与 post-processors 关联的行为,如 this unit test 所示。

您的注册码如下所示:

services.AddMediatR();
services.AddTransient(typeof(IRequestPostProcessor<,>), typeof(PostHandler<,>));
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));

那个behavior会得到你注册的所有post-processors并执行它们。

编辑

在对 post-processor 运行 进行了两次评论后,我查看了在 ASP.NET Core built-in DI 容器中注册 MediatR 的代码,它事实证明 IRequestPreProcessor<TRequest, TResponse>IRequestPostProcessor<TRequest, TResponse> 的实例会自动注册,如您所见 here。要让它们 运行 进入管道,剩下要做的就是注册关联的行为。那么必要的注册就是:

services.AddMediatR();
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPostProcessorBehavior<,>));

我在上面的评论中遇到了与 Larsi 相同的问题。我的代码看起来像这样

services.AddScoped<IPipelineBehavior<AddMessageRequest, MessageResponse>, RequestPostProcessorBehavior<AddMessageRequest, MessageResponse>>();

但该行为仍然执行了两次。我的解决方案是简单地不手动注册它,现在注册似乎以其他方式处理。

在我的情况下 services.AddMediatR(Assembly.GetExecutingAssembly()); 就足够了。

如果有人能详细说明这是为什么,那就太好了。