Skip to content

Commit

Permalink
Assume section name matches class name if no attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
tgharold committed Mar 5, 2020
1 parent b77e814 commit d8e54c9
Showing 1 changed file with 16 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System;
using System.Reflection;
using Example3Api.Attributes;
using Microsoft.Extensions.Configuration;
Expand All @@ -12,39 +11,44 @@ public static class IServiceCollectionExtensions
public static T ConfigureAndValidateSection<T, TValidator>(
this IServiceCollection services,
IConfiguration configuration
)
)
where T : class
where TValidator : class, IValidateOptions<T>
{
var sectionName = typeof(T).GetCustomAttribute<ConfigurationSectionNameAttribute>()?.SectionName
?? throw new ArgumentNullException(nameof(ConfigurationSectionNameAttribute));

var sectionName = GetSectionName<T>();

var configurationSection = configuration.GetSection(sectionName);

services.AddOptions<T>()
.Bind(configurationSection);

services.AddSingleton<IValidateOptions<T>, TValidator>();

return configurationSection.Get<T>();
}

public static T ConfigureSection<T>(
this IServiceCollection services,
IConfiguration configuration
)
)
where T : class
{
var sectionName = typeof(T).GetCustomAttribute<ConfigurationSectionNameAttribute>()?.SectionName
?? throw new ArgumentNullException(nameof(ConfigurationSectionNameAttribute));

var sectionName = GetSectionName<T>();

var configurationSection = configuration.GetSection(sectionName);

services.AddOptions<T>()
.Bind(configurationSection);

return configurationSection.Get<T>();
}

private static string GetSectionName<T>()
where T : class
{
// Assume that if there is no custom attribute that the section is named after the class
return typeof(T).GetCustomAttribute<ConfigurationSectionNameAttribute>()?.SectionName
?? typeof(T).Name;
}
}
}

0 comments on commit d8e54c9

Please sign in to comment.