.NET 6配置MediatR后验证器未触发问题及解决方法
MediatR验证管道未执行的问题及解决办法
我在测试项目中搭建CURD功能,使用了最新版本的MediatR NuGet包,配置代码如下:
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); services.AddMediatR(cfg => { cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()); cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>), ServiceLifetime.Transient); cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(LoggingBehaviour<,>), ServiceLifetime.Scoped); });
调用Mediator命令时,日志管道可以正常工作,但验证管道始终未执行。该配置代码写在.NET API项目的Program.cs中,项目引用了存放所有Command、Queries、ValidationBehaviour和LoggingBehaviour的Service项目,我查了不少线上资料都没能解决问题,想问问有没有类似配置且验证器能正常工作的案例?
问题解决
后来找到原因了:需要添加两种不同的验证管道实现,分别对应两种IRequest接口的泛型形式:
ValidationBehaviour1<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest ValidationBehaviour2<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
内容的提问来源于stack exchange,提问作者LittleFunny
相关产品推荐
相关产品推荐

