Skip to content

Commit 54fe9e0

Browse files
committed
Add extension
1 parent 59b5ce2 commit 54fe9e0

File tree

1 file changed

+30
-6
lines changed

1 file changed

+30
-6
lines changed

ConfigFluentValidation/Program.cs

Lines changed: 30 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,24 @@
11
using FluentValidation;
2+
using FluentValidation.Results;
23
using Microsoft.Extensions.Options;
34

45
var 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
713
builder.Services.AddScoped<IValidator<SlackApiSettings>, SlackApiSettingsValidator>();
814

15+
// 2. Register the settings
916
builder.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
1522
builder.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

Comments
 (0)