我正在尝试在我的测试项目中设置 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);
});
当中介调用命令时,我的日志管道正在工作。但验证器管道永远不会执行。我关注了在线资源,但无法使其发挥作用。
该代码在 Program.cs 内部调用,这是一个 .net API 项目,并引用了一个服务项目,其中存储了所有命令、查询、ValidatorBehaviour 和 LoggingBehaviour。
有人有类似的设置并且能够让验证器工作吗?
我找到了原因:我需要添加两个不同的验证器管道
ValidationBehaviour1<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest
ValidationBehaviour2<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>
如果您的解决方案包含多个项目,那么您应该注册多个程序集(每个项目一个)。目前,您只能通过
Assembly.GetExecutingAssembly()
注册包含您在帖子中共享的代码的程序集。
有多种方法可以获取所有项目程序集。一种方法是选择在程序集中定义的类并执行
Assembly.GetAssembly(typeof(YourClass))
(并对每个项目执行此操作)。
旁注:
MediatR 可以将代码存储库重塑为漂亮、干净的东西,但似乎很多人都会遇到像您刚才描述的那样的问题,即使人们曾经让它工作过一次。 我对 IGet 感到非常兴奋,用它你可以创建类似 MediatR 的结构和干净的代码,但在我看来,没有这些问题。
请使用
cfg.AddBehavior(typeof(IPipelineBehavior<,>) ...
来代替。