Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 281
letie Avatar asked Dec 02 '25 06:12

letie


2 Answers

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.AddValidatorsFromAssemblyContaining<AnyValidator>() // register validators
    builder.Services.AddFluentValidationAutoValidation(); // the same old MVC pipeline behavior
    builder.Services.AddFluentValidationClientsideAdapters(); // for client side
like image 86
Okan Karadag Avatar answered Dec 03 '25 20:12

Okan Karadag


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

like image 29
DonSleza4e Avatar answered Dec 03 '25 20:12

DonSleza4e



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!