Last active
September 8, 2018 05:34
-
-
Save wellingtonjhn/861c887e87e00a3b5f6cd98c0cb2ed8b to your computer and use it in GitHub Desktop.
Startup Filter for Settings Validation
This file contains hidden or 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
| public class ConfigurationSettingValidationStartupFilter : IStartupFilter | |
| { | |
| private readonly IEnumerable<ConfigurationSettings> _configurationSettings; | |
| private readonly ILogger<ConfigurationSettingValidationStartupFilter> _logger; | |
| public ConfigurationSettingValidationStartupFilter( | |
| IEnumerable<ConfigurationSettings> configurationSettings, | |
| ILogger<ConfigurationSettingValidationStartupFilter> logger) | |
| { | |
| _configurationSettings = configurationSettings; | |
| _logger = logger; | |
| } | |
| public Action<IApplicationBuilder> Configure(Action<IApplicationBuilder> next) | |
| { | |
| foreach (var settings in _configurationSettings) | |
| { | |
| if (settings.Validate()) | |
| { | |
| continue; | |
| } | |
| var settingsName = settings.GetType().Name; | |
| var message = $"Invalid {settingsName} configuration. {string.Join(",", settings.ValidationResult)}"; | |
| var exception = new InvalidOperationException(message); | |
| _logger.LogError(exception, "Invalid configuration. The application initialisation is aborted."); | |
| throw exception; | |
| } | |
| return next; | |
| } | |
| } |
This file contains hidden or 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
| public static class ConfigureOptionsExtensions | |
| { | |
| public static IServiceCollection RegisterSettings<TOptions>(this IServiceCollection services, IConfiguration configuration) | |
| where TOptions : class, new() | |
| { | |
| var name = typeof(TOptions).Name; | |
| services.Configure<TOptions>(configuration.GetSection(name)); | |
| services.AddSingleton(resolver => resolver.GetRequiredService<IOptions<TOptions>>().Value as ConfigurationSettings); | |
| return services; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment