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

Viewed 11006

I'm using "FluentValidation.AspNetCore" library (Version="8.6.2") for a .Net Core project.

What I would like to do is to register all my Validators automatically in Startup.cs class, using something like this (which is what I'm using now):

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

But the problem is that my validators are going to be moved to another assembly (required by client), so I can't use Startup as reference for the registration.

Is there a way I can do this without having to register the validators one by one?

4 Answers

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>());

You can use the official nuget package for that:

services.AddValidatorsFromAssemblyContaining<SomeValidator>();

or

services.AddValidatorsFromAssemblyContaining(typeof(SomeValidator));

or

services.AddValidatorsFromAssembly(typeof(SomeValidator).Assembly);

All possible DI options described here

AddFluentValidation() is deprecated.

source : https://github.com/FluentValidation/FluentValidation/issues/1965

old:

builder.Services.AddControllersWithViews().AddFluentValidation(fv => { });//or AddMvc(), AddMvcCore()

//or
builder.Services.AddFluentValidation(config => 
{
    config.ConfigureClientsideValidation(enabled: false);
});

new :

builder.Services.AddFluentValidationAutoValidation();
builder.Services.AddFluentValidationClientsideAdapters(); // for client side

Anyone know if registering the Validators like this works for grpc services?

services.AddValidatorsFromAssemblyContaining<SomeValidator>();

or

services.AddValidatorsFromAssemblyContaining(typeof(SomeValidator));
Related