AddFluentValidationAutoValidation configures FluentValidation for ASP.NET Core MVC and Razor Pages. Install the FluentValidation.AspNetCore package, call the method in Program.cs, and register validators with dependency injection. section 32.4.2
A typical setup follows these steps:
- Install FluentValidation.AspNetCore with the .NET CLI or a project package reference. section 32.4.2
- Call AddFluentValidationAutoValidation() while configuring services in Program.cs. section 32.4.2
- Register validators manually or discover them with AddValidatorsFromAssemblyContaining<T>(). section 32.5
- Set DisableDataAnnotationsValidation to true when FluentValidation should be the only validation system. section 32.4.2
Listing 32.15 Configuring FluentValidation in an ASP.NET Core application
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddValidatorsFromAssemblyContaining<Program>(); #1
builder.Services.AddFluentValidationAutoValidation( #2
x => x.DisableDataAnnotationsValidation = true) #2
.AddFluentValidationClientsideAdapters(); #3
ValidatorOptions.Global.LanguageManager.Enabled = false; #4
This configuration combines validator discovery, automatic validation, optional client-side adapters, and DataAnnotations control. section 32.4.2
Practical configuration
Register validators from the assembly containing Program, then enable automatic validation and disable DataAnnotations validation: builder.Services.AddValidatorsFromAssemblyContaining<Program>(); builder.Services.AddFluentValidationAutoValidation(x => x.DisableDataAnnotationsValidation = true);. Keeping validators near the models they validate is a practical organization choice, not a technical requirement. section 32.4.2
