Created
March 14, 2019 12:55
-
-
Save StefH/5c9f4de80ee76da9cd2d959b2e542ccb 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
using Microsoft.Extensions.Options; | |
using System; | |
using System.Configuration; | |
using System.Linq; | |
using System.Reflection; | |
namespace ConsoleApp | |
{ | |
public static class OptionsBuilderExtensions | |
{ | |
public static OptionsBuilder<TOptions> ConfigureFromAppSettings<TOptions>(this OptionsBuilder<TOptions> builder, bool useOptionNameAsPrefix = true) where TOptions : class | |
{ | |
Type optionsType = builder.GetType().GenericTypeArguments.First(); | |
string prefix = useOptionNameAsPrefix ? $"{optionsType.Name}." : string.Empty; | |
builder.Configure(configure => | |
{ | |
foreach (var property in optionsType.GetProperties(BindingFlags.Instance | BindingFlags.Public)) | |
{ | |
string fullName = $"{prefix}{property.Name}"; | |
string appSettingsValue = ConfigurationManager.AppSettings.Get(fullName); | |
property.SetValue(configure, Convert.ChangeType(appSettingsValue, property.PropertyType)); | |
} | |
}); | |
return builder; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment