Can I apply a prefix to all keys loaded from a configuration provider? #60458
Unanswered
wazzamatazz
asked this question in
Q&A
Replies: 1 comment 1 reply
-
I've worked around this before using the IEnumerable overload in the configuration provider; you build one configuration root with the values you want, and then enumerate its key/value pairs, adding a prefix to the key. Something like this: var rootOne = new ConfigurationBuilder()
.AddYourSource()
.Build();
realRoot.AddInMemoryCollection(AddPrefix(rootOne.AsEnumerable(), "prefix"));
static IEnumerable<KeyValuePair<string, string>> AddPrefix(IEnumerable<KeyValuePair<string, string>> values, string prefix)
{
foreach (var pair in values)
yield return new(ConfigurationPath.Combine(prefix, pair.Key), pair.Value);
} Unfortunately, this does not allow for things like reload tokens. I was looking into something like this at one point, but I couldn't figure out a good way to implement that without being confusing. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Say I have an options class like this:
In my startup code, I might bind these options as follows:
If I wanted to define individual items in the
MyOptions.Devices
collection in separate files, I could add additional JSON providers to myIConfigurationBuilder
and then define additional configuration files e.g.:This works well, but I'd like to know if there is a built-in way to automatically add a prefix to all keys loaded from a given provider? In my example above, I'd like to be able to prefix all keys from JSON files matching
devices.*.json
withMyApp:MyOptions:Devices:
, so that the JSON file itself could be simplified to something like this:Is this something that is possible out of the box, or would I have to write a custom JSON configuration provider to accomplish this? Looking at the source for the JsonConfigurationFileParser, this could be accomplished by injecting an initial context into the parser containing the prefix, but since the class itself is
internal
and theEnterContext
method isprivate
, there's no obvious way to accomplish it without copying and modifying this code, unless it is possible to tell the configuration builder itself to apply a prefix to keys from certain sources?Beta Was this translation helpful? Give feedback.
All reactions