diff --git a/Example3-IValidateOptions/src/Example3Api/Extensions/IServiceCollectionExtensions.cs b/Example3-IValidateOptions/src/Example3Api/Extensions/IServiceCollectionExtensions.cs index 4fe82c6..4fa6fbb 100644 --- a/Example3-IValidateOptions/src/Example3Api/Extensions/IServiceCollectionExtensions.cs +++ b/Example3-IValidateOptions/src/Example3Api/Extensions/IServiceCollectionExtensions.cs @@ -1,4 +1,3 @@ -using System; using System.Reflection; using Example3Api.Attributes; using Microsoft.Extensions.Configuration; @@ -12,39 +11,44 @@ public static class IServiceCollectionExtensions public static T ConfigureAndValidateSection( this IServiceCollection services, IConfiguration configuration - ) + ) where T : class where TValidator : class, IValidateOptions { - var sectionName = typeof(T).GetCustomAttribute()?.SectionName - ?? throw new ArgumentNullException(nameof(ConfigurationSectionNameAttribute)); - + var sectionName = GetSectionName(); + var configurationSection = configuration.GetSection(sectionName); services.AddOptions() .Bind(configurationSection); - + services.AddSingleton, TValidator>(); - + return configurationSection.Get(); } public static T ConfigureSection( this IServiceCollection services, IConfiguration configuration - ) + ) where T : class { - var sectionName = typeof(T).GetCustomAttribute()?.SectionName - ?? throw new ArgumentNullException(nameof(ConfigurationSectionNameAttribute)); - + var sectionName = GetSectionName(); + var configurationSection = configuration.GetSection(sectionName); services.AddOptions() .Bind(configurationSection); - + return configurationSection.Get(); } + private static string GetSectionName() + where T : class + { + // Assume that if there is no custom attribute that the section is named after the class + return typeof(T).GetCustomAttribute()?.SectionName + ?? typeof(T).Name; + } } } \ No newline at end of file