Skip to content

Instantly share code, notes, and snippets.

@MrZoidberg
Created July 28, 2022 10:35
Show Gist options
  • Save MrZoidberg/1841b0da587cf9a5f6949252ed30541d to your computer and use it in GitHub Desktop.
Save MrZoidberg/1841b0da587cf9a5f6949252ed30541d to your computer and use it in GitHub Desktop.
/// <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