Created
July 28, 2022 10:35
-
-
Save MrZoidberg/1841b0da587cf9a5f6949252ed30541d to your computer and use it in GitHub Desktop.
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
/// <summary> | |
/// Registers <see cref="IOptions{TOptions}"/> and <typeparamref name="TOptions"/> to the services container. | |
/// Also runs data annotation validation on application startup. | |
/// </summary> | |
/// <typeparam name="TOptions">The type of the options.</typeparam> | |
/// <param name="services">The services collection.</param> | |
/// <param name="configuration">The configuration.</param> | |
/// <returns>The same services collection.</returns> | |
public static IServiceCollection ConfigureAndValidateSingleton<TOptions>( | |
this IServiceCollection services, | |
IConfiguration configuration) | |
where TOptions : class, new() | |
{ | |
ArgumentNullException.ThrowIfNull(services); | |
ArgumentNullException.ThrowIfNull(configuration); | |
services | |
.AddOptions<TOptions>() | |
.Bind(configuration) | |
.ValidateDataAnnotations() | |
.ValidateOnStart(); | |
return services.AddSingleton(x => x.GetRequiredService<IOptions<TOptions>>().Value); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment