How can I bind a configuration section to a KeyValuePair<string, string>? #97039
Unanswered
paulomorgado
asked this question in
Q&A
Replies: 1 comment 3 replies
-
I don't know of a way to directly use KeyValuePair in this situation. Since structs can always be initialized without using a parameterized constructor, the binder foregoes using KeyValuePair's parameterized constructor when instantiating the KeyValuePair instance, but is then unsuccessful in setting the Key/Value properties as they lack setters. But if your scenario isn't too involved, one possible workaround might be using your own SettableKVP type with settable properties and an implicit/explicit conversion operator which converts a SettableKVP instance to a KeyValuePair instance. KeyValuePair<string, string> kvp = configuration.GetSection("kvp").Get<SettableKVP<string, string>>();
public struct SettableKVP<TKey, TValue>
{
public TKey Key { get; set; }
public TValue Value { get; set; }
public static implicit operator KeyValuePair<TKey, TValue>(SettableKVP<TKey, TValue> kvp)
=> new(kvp.Key, kvp.Value);
} |
Beta Was this translation helpful? Give feedback.
3 replies
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.
-
kvp.Key
andkvp.Value
arenull
.Beta Was this translation helpful? Give feedback.
All reactions