Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tarekgh/8ff6d0a4149034cee274c5dc12028418 to your computer and use it in GitHub Desktop.
Save tarekgh/8ff6d0a4149034cee274c5dc12028418 to your computer and use it in GitHub Desktop.
Workaround for allow using `.` in the environment variables configuration
// Can define the environment variable with three underscores ___ in the places you want dot.
// Logging__LogLevel__Microsoft___Hosting___Lifetime=Information <-- Logging:LogLevel:Microsoft.Hosting.Lifetime=Information
public class CustomEnvironmentVariablesConfigurationProvider : EnvironmentVariablesConfigurationProvider
{
internal const string DefaultDotReplacement = ":_";
private string _dotReplacement;
public CustomEnvironmentVariablesConfigurationProvider(string? dotReplacement = DefaultDotReplacement) : base()
{
_dotReplacement = dotReplacement ?? DefaultDotReplacement;
}
public CustomEnvironmentVariablesConfigurationProvider(string? prefix, string? dotReplacment = DefaultDotReplacement) : base(prefix)
{
_dotReplacement = dotReplacment ?? DefaultDotReplacement;
}
public override void Load()
{
base.Load();
Dictionary<string, string?> data = new Dictionary<string, string?>();
foreach (KeyValuePair<string, string?> kvp in Data)
{
if (kvp.Key.Contains(_dotReplacement))
{
data.Add(kvp.Key.Replace(_dotReplacement, ".", StringComparison.OrdinalIgnoreCase), kvp.Value);
}
else
{
data.Add(kvp.Key, kvp.Value);
}
}
Data = data;
}
}
public class CustomEnvironmentVariablesConfigurationSource : IConfigurationSource
{
public string? Prefix { get; set; }
public string? DotReplacement { get; set; }
public IConfigurationProvider Build(IConfigurationBuilder builder)
{
return new CustomEnvironmentVariablesConfigurationProvider(Prefix, DotReplacement);
}
}
public static class CustomEnvironmentVariablesExtensions
{
public static IConfigurationBuilder AddCustomEnvironmentVariables(this IConfigurationBuilder configurationBuilder)
{
configurationBuilder.Add(new CustomEnvironmentVariablesConfigurationSource());
return configurationBuilder;
}
public static IConfigurationBuilder AddCustomEnvironmentVariables(this IConfigurationBuilder configurationBuilder, string? prefix, string? dotReplacement = CustomEnvironmentVariablesConfigurationProvider.DefaultDotReplacement)
{
configurationBuilder.Add(new CustomEnvironmentVariablesConfigurationSource { Prefix = prefix, DotReplacement = dotReplacement });
return configurationBuilder;
}
public static IConfigurationBuilder AddCustomEnvironmentVariables(this IConfigurationBuilder builder, Action<CustomEnvironmentVariablesConfigurationSource>? configureSource) => builder.Add(configureSource);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment