Created
January 15, 2018 14:06
-
-
Save alfeg/0998a4aefe207f1f6d7f61abd1a99794 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
public class PerHostJsonConfigBuilder : ConfigurationBuilder | |
{ | |
public string Directory { get; set; } | |
JObject hostConfig = null; | |
public override void Initialize(string name, NameValueCollection config) | |
{ | |
base.Initialize(name, config); | |
JObject LoadByHostName(string host) | |
{ | |
string appName = config["appName"] ?? null; | |
if (appName != null) appName = "." + appName; | |
var configName = $"{host}{appName ?? ""}.config.json"; | |
var fileName = Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, | |
Directory, | |
configName); | |
if (File.Exists(fileName)) | |
{ | |
System.Diagnostics.Trace.TraceInformation($"Loaded config {configName}"); | |
return JObject.Parse(File.ReadAllText(fileName)); | |
} | |
return null; | |
} | |
hostConfig = LoadByHostName(config["default"] ?? "Production") ?? LoadByHostName(Environment.MachineName); | |
} | |
public override ConfigurationSection ProcessConfigurationSection(ConfigurationSection configSection) | |
{ | |
IEnumerable<(string key, string value)> HostSettings(string section) | |
{ | |
if (hostConfig == null) yield break; | |
var appSettings = hostConfig[section]; | |
if (appSettings != null && appSettings is JObject settings) | |
{ | |
foreach (var property in settings.Properties()) | |
{ | |
yield return (property.Name, property.Value.ToString()); | |
} | |
} | |
} | |
if (configSection is AppSettingsSection app) | |
{ | |
foreach (var setting in HostSettings("AppSettings")) | |
{ | |
app.Settings.Remove(setting.key); | |
app.Settings.Add(setting.key, setting.value); | |
} | |
} | |
if (configSection is ConnectionStringsSection connection) | |
{ | |
foreach (var setting in HostSettings("ConnectionStrings")) | |
{ | |
var connectionString = connection.ConnectionStrings[setting.key]; | |
if (connectionString != null) | |
{ | |
connectionString.ConnectionString = setting.value; | |
} | |
} | |
} | |
return base.ProcessConfigurationSection(configSection); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment