skip to content

In an ASP.NET Core 10 Minimal API, how do you register FluentValidation validators, run an injected IValidator<LoanApplication>, and return a ValidationProblem?

level: juniorimportance: must knowfreq 62%

answer

  1. FluentValidation.DependencyInjectionExtensions package
  2. AddValidatorsFromAssemblyContaining<T>()
  3. inject IValidator<T>, not the class
  4. await ValidateAsync(model, ct)
  5. ToDictionary() into TypedResults.ValidationProblem

basics

~10 s

Call AddValidatorsFromAssemblyContaining<LoanApplicationValidator>() at startup, inject IValidator<LoanApplication> into the handler, await ValidateAsync, and when IsValid is false return TypedResults.ValidationProblem(result.ToDictionary()), a 400 with validation problem details.

solid answer

~40 s

FluentValidation does not hook into Minimal APIs by itself, so the wiring is explicit. The `FluentValidation.DependencyInjectionExtensions` package adds `AddValidatorsFromAssemblyContaining<LoanApplicationValidator>()`, which scans that assembly and registers each validator as `IValidator<T>` (scoped by default). The handler declares an `IValidator<LoanApplication>` parameter, which Minimal APIs resolve from DI, and calls `await validator.ValidateAsync(application, cancellationToken)`. The `ValidationResult` exposes `IsValid` and `Errors`; `ToDictionary()` groups the failures into an `IDictionary<string, string[]>` keyed by property name, exactly what `TypedResults.ValidationProblem(...)` takes, and that result writes a 400 with an `errors` object. In an MVC controller the same validator is constructor-injected; there you either copy errors into `ModelState` and return `ValidationProblem(ModelState)`, or pass the dictionary to `new ValidationProblemDetails(...)`.

go deeper

for a junior

Remember the four steps: register with AddValidatorsFromAssemblyContaining, inject IValidator<T>, await ValidateAsync, return ValidationProblem from ToDictionary.

for a middle

Explain what the scan registers, why ValidateAsync and the cancellation token matter, and how keys in ToDictionary map to property paths.

for a senior

Keep one validation error contract across Minimal APIs and controllers, choosing between ValidationProblemDetails and ModelState merging deliberately.

for a principal

Decide whether FluentValidation, built-in DataAnnotations or both own request validation, considering consistency, testability and the cost of two rule styles.

## The pieces and where they come from | Piece | Package / namespace | Role | |---|---|---| | `AbstractValidator<LoanApplication>` | `FluentValidation` | where the rules live (rule writing is its own topic) | | `AddValidatorsFromAssemblyContaining<T>()` | `FluentValidation.DependencyInjectionExtensions` package, `FluentValidation` namespace | scans an assembly and registers validators | | `IValidator<T>` | `FluentValidation` | the service you inject | | `ValidationResult` | `FluentValidation.Results` | `IsValid`, `Errors`, `ToDictionary()` | | `TypedResults.ValidationProblem` | ASP.NET Core `Microsoft.AspNetCore.Http` | writes the 400 response | A naming trap: `ValidationResult` also exists in `System.ComponentModel.DataAnnotations`. In a file that imports both namespaces, qualify or alias one of them. ## Registration ```csharp builder.Services.AddValidatorsFromAssemblyContaining<LoanApplicationValidator>(); ``` The scan finds every public, non-abstract, non-generic-definition validator in the assembly that contains `LoanApplicationValidator` and registers it twice: as `IValidator<LoanApplication>` and as its own concrete type. The default lifetime is **scoped**. Despite what some samples write, the extension method sits in the `FluentValidation` namespace, not in a `FluentValidation.DependencyInjectionExtensions` namespace. ## The handler ```csharp app.MapPost("/loan-applications", async Task<Results<Created<LoanDecision>, ValidationProblem>> ( LoanApplication application, IValidator<LoanApplication> validator, ILoanService loans, CancellationToken cancellationToken) => { var result = await validator.ValidateAsync(application, cancellationToken); if (!result.IsValid) return TypedResults.ValidationProblem(result.ToDictionary()); var decision = await loans.SubmitAsync(application, cancellationToken); return TypedResults.Created($"/loan-applications/{decision.Id}", decision); }); ``` Step by step: 1. Minimal APIs bind `application` from the JSON body and resolve `validator` and `loans` from DI. 2. `ValidateAsync` runs every rule, including asynchronous ones such as a credit-bureau check, and honours the cancellation token. 3. `result.IsValid` is `true` only when `Errors` is empty. 4. `ToDictionary()` groups `Errors` by `PropertyName`, giving keys such as `Amount` or `Applicant.Email` with an array of messages each. 5. `TypedResults.ValidationProblem` produces a **400 Bad Request** with an `HttpValidationProblemDetails` body whose `errors` member holds that dictionary. The typed union return also lets the OpenAPI document list both outcomes. ## The same validator in an MVC controller ```csharp [ApiController, Route("api/loan-applications")] public class LoanApplicationsController(IValidator<LoanApplication> validator) : ControllerBase { [HttpPost] public async Task<IActionResult> Submit(LoanApplication application, CancellationToken ct) { var result = await validator.ValidateAsync(application, ct); if (!result.IsValid) return ValidationProblem(new ValidationProblemDetails(result.ToDictionary())); return Accepted(); } } ``` Two options exist for controllers: - `new ValidationProblemDetails(result.ToDictionary())` passed to `ControllerBase.ValidationProblem(...)` returns the dictionary directly. - Copying each failure with `ModelState.AddModelError(error.PropertyName, error.ErrorMessage)` and returning `ValidationProblem(ModelState)` (or redisplaying a view) merges FluentValidation errors with any DataAnnotations errors already in `ModelState`. ## Common mistakes - Injecting the concrete `LoanApplicationValidator` everywhere: it works because the scan registers it, but it ties handlers to a class instead of the `IValidator<T>` abstraction and makes test doubles harder. - Calling `Validate` instead of `ValidateAsync`: a validator with async rules throws. - Returning `TypedResults.BadRequest(result.Errors)`: it serializes FluentValidation's failure objects instead of the standard validation problem shape clients expect. - `TypedResults.ValidationProblem` is always 400. For another status such as 422, use `Results.ValidationProblem(errors, statusCode: 422)`. ## What interviewers listen for - The package and the one-line registration. - Injecting `IValidator<T>` and awaiting `ValidateAsync` with the request's cancellation token. - `ToDictionary()` feeding `ValidationProblem`, and what the client receives.

  • Why does the error key come out as Applicant.Email rather than Email?
    FluentValidation sets each failure's `PropertyName` to the full path of the property it validated, so a rule on a child validator for `Applicant` reports `Applicant.Email`, and collection items report paths such as `Guarantors[0].Name`. `ToDictionary()` groups by that `PropertyName`, so the keys in the problem details match those paths.
  • How would you return 422 instead of 400 for FluentValidation failures in a Minimal API?
    `TypedResults.ValidationProblem` always produces 400. Use `Results.ValidationProblem(result.ToDictionary(), statusCode: 422)`, which accepts a status code, or write your own result type. Keep the dictionary shape so clients see the same `errors` object either way.
  • In an MVC view, how do FluentValidation errors reach the field-level messages?
    Copy them into `ModelState`: for each `ValidationFailure`, call `ModelState.AddModelError(failure.PropertyName, failure.ErrorMessage)`, then return the view. The validation tag helpers read `ModelState`, so the messages appear beside the matching inputs just like DataAnnotations errors.

  • Registering validators with AddValidatorsFromAssemblyContaining makes Minimal APIs validate requests automatically.
  • IValidatorFactory is the current way to obtain validators in ASP.NET Core.
  • ValidationResult.ToDictionary returns one message per property, dropping the rest.
  • TypedResults.ValidationProblem accepts a status code such as 422.
  • Validators must be newed up in each handler because they cannot be injected.

Assumes ASP.NET Core 10 with FluentValidation 12.1; ValidationResult.ToDictionary has existed since FluentValidation 11.1, and TypedResults.ValidationProblem is the Minimal API result used here.