11using FluentValidation ;
2+ using FluentValidation . Results ;
23using Microsoft . Extensions . Options ;
34
45var builder = WebApplication . CreateBuilder ( args ) ;
56
6- // Register the validator
7+ // Use the extension method
8+ builder . Services . AddWithValidation < SlackApiSettings , SlackApiSettingsValidator > ( "SlackApi" ) ;
9+
10+ // OR:
11+
12+ // 1. Register the validator
713builder . Services . AddScoped < IValidator < SlackApiSettings > , SlackApiSettingsValidator > ( ) ;
814
15+ // 2. Register the settings
916builder . Services . AddOptions < SlackApiSettings > ( )
1017 . BindConfiguration ( "SlackApi" )
1118 . ValidateFluentValidation ( ) // <- Enable validation
1219 . ValidateOnStart ( ) ; // <- Validate on app start
1320
14- // Explicitly register the settings object by delegating to the IOptions object
21+ // Optional: Explicitly register the settings object by delegating to the IOptions object
1522builder . Services . AddSingleton ( resolver =>
1623 resolver . GetRequiredService < IOptions < SlackApiSettings > > ( ) . Value ) ;
1724
@@ -81,12 +88,12 @@ public ValidateOptionsResult Validate(string? name, TOptions options)
8188
8289 // Ensure options are provided to validate against
8390 ArgumentNullException . ThrowIfNull ( options ) ;
84-
91+
8592 // Validators are registered as scoped, so need to create a scope,
8693 // as we will be called from the root scope
87- using var scope = _serviceProvider . CreateScope ( ) ;
88- var validator = scope . ServiceProvider . GetRequiredService < IValidator < TOptions > > ( ) ;
89- var results = validator . Validate ( options ) ;
94+ using IServiceScope scope = _serviceProvider . CreateScope ( ) ;
95+ IValidator < TOptions > validator = scope . ServiceProvider . GetRequiredService < IValidator < TOptions > > ( ) ;
96+ ValidationResult ? results = validator . Validate ( options ) ;
9097 if ( results . IsValid )
9198 {
9299 return ValidateOptionsResult . Success ;
@@ -101,4 +108,21 @@ public ValidateOptionsResult Validate(string? name, TOptions options)
101108
102109 return ValidateOptionsResult . Fail ( errors ) ;
103110 }
111+ }
112+
113+ public static class FluentValidationOptionsExtensions
114+ {
115+ public static OptionsBuilder < TOptions > AddWithValidation < TOptions , TValidator > (
116+ this IServiceCollection services ,
117+ string configurationSection )
118+ where TOptions : class
119+ where TValidator : class , IValidator < TOptions >
120+ {
121+ services . AddScoped < IValidator < TOptions > , TValidator > ( ) ;
122+
123+ return services . AddOptions < TOptions > ( )
124+ . BindConfiguration ( configurationSection )
125+ . ValidateFluentValidation ( )
126+ . ValidateOnStart ( ) ;
127+ }
104128}
0 commit comments