Path: redb/redb.Templates/templates/redb-bff/RedbBff.Host/ContextConfiguration.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Host/ContextConfiguration.cs
----
using Microsoft.Extensions.Configuration;
using redb.Route.Abstractions;
namespace RedbBff.Host;
///
/// The context configuration the way a Tsak worker builds it, in miniature. Each layer deep-merges over
/// the previous one, later layers win:
///
/// - the module's RedbBff.Backend.config.json,
/// - Tsak:Contexts:{context}:Override of the host configuration.
///
/// Every root key then becomes a property of the route context; a section becomes a dictionary. So the
/// same keys and the same environment variables work here and on a Tsak worker.
///
public static class ContextConfiguration
{
/// The context the module asks for, from its ContextName.
public static string ContextNameOf(string moduleConfigPath) =>
new ConfigurationBuilder().AddJsonFile(moduleConfigPath, optional: false).Build()["ContextName"]
?? throw new InvalidOperationException($"{moduleConfigPath} has no ContextName.");
public static IDictionary Build(IConfiguration host, string contextName, string moduleConfigPath)
{
var config = Read(new ConfigurationBuilder().AddJsonFile(moduleConfigPath, optional: false).Build());
Merge(config, Read(host.GetSection($"Tsak:Contexts:{contextName}:Override")));
return config;
}
public static void ApplyTo(IRouteContext context, IDictionary config)
{
foreach (var (key, value) in config)
{
if (value is not null)
context.SetProperty(key, value);
}
}
private static Dictionary Read(IConfiguration section)
{
var result = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var child in section.GetChildren())
result[child.Key] = child.GetChildren().Any() ? Read(child) : child.Value;
return result;
}
private static void Merge(IDictionary target, IDictionary layer)
{
foreach (var (key, value) in layer)
{
if (value is IDictionary nested
&& target.TryGetValue(key, out var existing) && existing is IDictionary current)
Merge(current, nested);
else
target[key] = value;
}
}
}