Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register validators from more than one assembly in FluentValidation?

I have FluentValidators in more than one assembly. In prior versions of FluentValidation, I was able to register like this:

services.AddMvc()
  .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyOne>())
  .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyTwo>());

But, this now results in the following error:

Exception thrown: 'System.InvalidOperationException' in System.Linq.dll
An exception of type 'System.InvalidOperationException' occurred in System.Linq.dll but was not handled in user code
Sequence contains more than one matching element

Is this no longer allowed? If not, what is the proper way to do this?

like image 740
stickian Avatar asked Feb 01 '18 16:02

stickian


2 Answers

I got the same error after upgrading FluentValidation.AspNetCore from 7.2.1 to 7.4.0 (as well as upgrading to ASP.NET Core 2.0).

I solved it by only calling .AddFluentValidaton(...) once, like this:

services.AddMvc()
  .AddFluentValidation(fv => {
    fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyOne>());
    fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyTwo>());
   });
like image 104
coder925 Avatar answered Nov 06 '22 00:11

coder925


This is the correct syntax to add as many assemblies as possible.

services
  .AddMvc()
  .AddFluentValidation(fv => {
    fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyOne>();
    fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyTwo>();
    fv.RegisterValidatorsFromAssemblyContaining<ClassInAssemblyThree>();
   });
like image 29
Coder Absolute Avatar answered Nov 06 '22 02:11

Coder Absolute