FluentValidation:如何从另一个程序集自动注册所有验证器?

FluentValidation: How to register all validators automatically from another assembly?

我正在为 .Net Core 项目使用“FluentValidation.AspNetCore”库(版本=“8.6.2”)。

我想做的是在 Startup.cs class 中自动注册我所有的验证器,使用类似这样的东西(我现在正在使用):

services.AddControllers().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<Startup>());

但问题是我的验证器将被移动到另一个程序集(客户端需要),所以我不能使用 Startup 作为注册参考。

有没有一种方法可以做到这一点而不必一个一个地注册验证器?

For registering Validator, there are three ways.

  1. Registering each validator in Service with AddTransient.
  2. Registering using “RegisterValidatorsFromAssemblyContaining” method registers all validators derived from AbstractValidator class within the assembly containing the specified type.
  3. Registering using “RegisterValidatorsFromAssembly” method.

来源here

如果您使用选项 2 并将代码中的 Startup 替换为从另一个程序集的 AbstractValidator 派生的任何 class,它将注册 all 来自该程序集的验证器

示例:

services.AddControllers().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<AnotherValidationClass>());