Skip to content

Instantly share code, notes, and snippets.

@StefH
Created March 14, 2019 12:55
Show Gist options
  • Save StefH/5c9f4de80ee76da9cd2d959b2e542ccb to your computer and use it in GitHub Desktop.
Save StefH/5c9f4de80ee76da9cd2d959b2e542ccb to your computer and use it in GitHub Desktop.
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