Home > database >  How to add multiple fluentvalidation classes from another project automatically
How to add multiple fluentvalidation classes from another project automatically

Time:01-12

I have a large project with many fluentvalidation classes that are in a separate project to Startup. I'm trying to add them all without adding a line for each one like I have currently:

services.AddControllers().AddFluentValidation(s => 
{
    s.RegisterValidatorsFromAssemblyContaining<Validation1>();
    s.RegisterValidatorsFromAssemblyContaining<Validation2>();
    ...
});

Is there a simpler way?

CodePudding user response:

Found a workaround creating a blank class and interface (which I named ValidationLink), and inheriting the interface in the validation classes.

services.AddControllers().AddFluentValidation(s => 
{
    s.RegisterValidatorsFromAssemblyContaining<ValidationLink>();
});
public class Validator1 : AbstractValidator<Class1>, IValidationLink
{
...
}

CodePudding user response:

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.

source here

If you use option number 2 and replace Startup in your code with any class derived from AbstractValidator from another assembly, it will register all validators from that assembly

Example:

services.AddControllers().AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<AnotherValidationClass>());
  •  Tags:  
  • Related