Skip to content

Commit

Permalink
ThreeMammals#651 merge custom properties
Browse files Browse the repository at this point in the history
  • Loading branch information
jlukawska authored and raman-m committed Nov 22, 2023
1 parent 40fa20f commit 8e4a64d
Showing 1 changed file with 29 additions and 5 deletions.
34 changes: 29 additions & 5 deletions src/Ocelot/DependencyInjection/ConfigurationBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,10 @@ public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder
.Where(fi => reg.IsMatch(fi.Name) && fi.Name != excludeConfigName)
.ToArray();

var fileConfiguration = new FileConfiguration();
dynamic fileConfiguration = new ExpandoObject();
fileConfiguration.GlobalConfiguration = new ExpandoObject();
fileConfiguration.Aggregates = new List<object>();
fileConfiguration.ReRoutes = new List<object>();

foreach (var file in files)
{
Expand All @@ -81,15 +84,15 @@ public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder

var lines = File.ReadAllText(file.FullName);

var config = JsonConvert.DeserializeObject<FileConfiguration>(lines);
dynamic config = JsonConvert.DeserializeObject<ExpandoObject>(lines);

if (file.Name.Equals(GlobalConfigFile, StringComparison.OrdinalIgnoreCase))
{
fileConfiguration.GlobalConfiguration = config.GlobalConfiguration;
TryAddSection(fileConfiguration, config, nameof(FileConfiguration.GlobalConfiguration));
}

fileConfiguration.Aggregates.AddRange(config.Aggregates);
fileConfiguration.Routes.AddRange(config.Routes);
TryAddSection(fileConfiguration, config, nameof(FileConfiguration.Aggregates));
TryAddSection(fileConfiguration, config, nameof(FileConfiguration.ReRoutes));
}

return builder.AddOcelot(fileConfiguration);
Expand All @@ -110,5 +113,26 @@ public static IConfigurationBuilder AddOcelot(this IConfigurationBuilder builder

return builder.AddJsonFile(PrimaryConfigFile, false, false);
}

private static void TryAddSection(ExpandoObject mergedConfig, ExpandoObject config, string sectionName)
{
var configAsDict = config as IDictionary<string, object>;
var mergedConfigAsDict = mergedConfig as IDictionary<string, object>;
if (configAsDict.ContainsKey(sectionName) && mergedConfigAsDict.ContainsKey(sectionName))
{
var mergedSectionAsExpando = mergedConfigAsDict[sectionName] as ExpandoObject;
if (mergedSectionAsExpando != null)
{
mergedConfigAsDict[sectionName] = configAsDict[sectionName];
}
else
{
var mergedSectionAsList = mergedConfigAsDict[sectionName] as List<object>;
var sectionAsList = configAsDict[sectionName] as List<object>;

mergedSectionAsList.AddRange(sectionAsList);
}
}
}
}
}

0 comments on commit 8e4a64d

Please sign in to comment.