Skip to content

Instantly share code, notes, and snippets.

@beachside-project
Created March 29, 2021 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beachside-project/5f9f8b9ca48cb5fee40cc04b666c4812 to your computer and use it in GitHub Desktop.
Save beachside-project/5f9f8b9ca48cb5fee40cc04b666c4812 to your computer and use it in GitHub Desktop.
OptionsPatternSamples - OptionBuilderExtensions
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