jasontaylordev / CleanArchitecture

Clean Architecture Solution Template for ASP.NET Core
MIT License
16.58k stars 3.56k forks source link

Repeatedly validated twice in AbstractValidator class #92

Closed walter-la closed 4 years ago

walter-la commented 4 years ago

Describe the bug A class that inherit AbstractValidator class will execute twice when a class that implement IRequest interface put parameters of method of controller class.

The reason is first time it happens in FluentValidationModelValidatorProvider class and second time happens in RequestValidationBehavior class.

If my AbstractValidator class has things of long time checking(ex: access Database), it will spend much time, and I think there is no need to do twice.

To Reproduce Steps to reproduce the behavior:

  1. Remove [Authorize] from TodoListsController.
  2. Start debugging the default CleanArchitecture project.
  3. Set a breakpoint at BeUniqueTitle's method of CreateTodoListCommandValidator class
  4. Using Swagger call /api/TodoLists
  5. Observe the breakpoint will be executed twice.

Expected behavior

It should be only validated once in the same AbstractValidator.

I think FluentValidationModelValidatorProvider doesn't need to be called, because RequestValidationBehavior is real to throw new ValidationException but FluentValidationModelValidatorProvider is not.

Screenshots image

Additional context Currently, I will add below code in ConfigureServices of Startup, because I don't know how to correctly remove it and I didn't find AddFluentValidation has related option.

services.AddMvcOptions(options =>
{
    // avoid AbstractValidator validate again in Controller ModelValidator
    var fluentValidationModelValidatorProvider
        = options.ModelValidatorProviders.FirstOrDefault(x => x.GetType().Name.Contains("FluentValidationModelValidatorProvider"));
    if (fluentValidationModelValidatorProvider != null)
    {
        options.ModelValidatorProviders.Remove(fluentValidationModelValidatorProvider);
    }
});
jasontaylordev commented 4 years ago

Thanks for reporting this issue. I've resolved by removing FluentValidation from Web UI and wiring up the validators in Application.