Created
March 29, 2021 09:14
-
-
Save beachside-project/5f9f8b9ca48cb5fee40cc04b666c4812 to your computer and use it in GitHub Desktop.
OptionsPatternSamples - OptionBuilderExtensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.Options; | |
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel.DataAnnotations; | |
using System.Linq; | |
namespace OptionsPatternSamples.Extensions | |
{ | |
public static class OptionBuilderExtensions | |
{ | |
public static OptionsBuilder<TOptions> ValidateDataAnnotations<TOptions>(this OptionsBuilder<TOptions> builder) where TOptions : class | |
{ | |
return builder.PostConfigure(options => | |
{ | |
var validationResults = new List<ValidationResult>(); | |
var validationContext = new ValidationContext(options); | |
var isValid = Validator.TryValidateObject(options, validationContext, validationResults); | |
if (isValid) return; | |
var message = string.Join("\n - ", validationResults.Select(v => v.ErrorMessage)); | |
throw new Exception($"{options.GetType()} is invalid:\n - {message}"); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment