Repository navigation
Description
Background and Motivation
I am trying to use JSON configuration settings that have names such as "some.flag" that get loaded into the IConfiguration dictionary. The key itself is mapped via JsonPropertyNameAttribute on my classes. The Binder project does not know of anything outside of the objects property names when it attempts to lookup the value by property name in the configuration dictionary.
What would be useful is to add custom binding attribute to identify a "known" name within the configuration dictionary that may not match the actual property name.
These lookups can be enabled by a new custom binding options attribute.
Proposed API
Naming I was leaning towards ConfigurationKeyNameAttribute to also map with class file names within the project. Within the context of configuration binder it could also be fitting for BindingKeyNameAttribute. Naming is hard.
namespace Microsoft.Extensions.Configuration
{
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
+ public sealed class ConfigurationKeyNameAttribute : Attribute
+ {
+ public string Name { get; }
+
+ public ConfigurationKeyNameAttribute(string name)
+ {
+ Name = name;
+ }
+ }
} private static void BindProperty(PropertyInfo property, object instance, IConfiguration config, BinderOptions options)
{
// We don't support set only, non public, or indexer properties
if (property.GetMethod == null ||
(!options.BindNonPublicProperties && !property.GetMethod.IsPublic) ||
property.GetMethod.GetParameters().Length > 0)
{
return;
}
object propertyValue = property.GetValue(instance);
bool hasSetter = property.SetMethod != null && (property.SetMethod.IsPublic || options.BindNonPublicProperties);
if (propertyValue == null && !hasSetter)
{
// Property doesn't have a value and we cannot set it so there is no
// point in going further down the graph
return;
}
- propertyValue = BindInstance(property.PropertyType, propertyValue, config.GetSection(property.Name), options);
+ propertyValue = GetPropertyValue(property, instance, config, options);
if (propertyValue != null && hasSetter)
{
property.SetValue(instance, propertyValue);
}
}
+ private static object GetPropertyValue(PropertyInfo property, object instance, IConfiguration config, BinderOptions options)
+ {
+ object propertyValue;
+ var propertyName = GetPropertyAttributeKeyName(property);
+
+ if (string.IsNullOrEmpty(propertyName))
+ propertyName = property.Name;
+
+ return BindInstance(property.PropertyType, propertyValue, config.GetSection(propertyName), options);
+ }
+
+ private static string GetPropertyAttributeKeyName(MemberInfo property)
+ {
+ if (property == null)
+ return string.Empty;
+
+ foreach (var attributeData in property.GetCustomAttributesData())
+ {
+ if (attributeData.AttributeType != typeof(ConfigurationKeyNameAttribute)) continue;
+ var constructorArgument = attributeData.ConstructorArguments.FirstOrDefault();
+ if (constructorArgument.ArgumentType == typeof(string))
+ return constructorArgument.Value?.ToString() ?? string.Empty;
+ }
+
+ return string.Empty;
+ }Usage Examples
Currently if there exists a class the behavior of the binder is to look at the dictionary created from external data sources like XML or typically JSON. A somewhat typical example of a .Net class with custom JSON property attributes:
public class Person
{
[ConfigurationKeyName("first_name")]
[JsonPropertyName("last_name")]
public string LastName { get; set; }
}Decorating the new property with the custom binding attribute I've proposed the binder will be able to map the dictionary name to the custom property name during the binding operation.
public class ComplexOptions
{
[ConfigurationKeyName(Name = "Named_Property")]
public string NamedProperty { get; set; }
}
public class DerivedOptions : ComplexOptions
{
}
[Fact]
public void CanBindAttributesIConfigurationSection()
{
var dic = new Dictionary<string, string>
{
{"Section:Named_Property", "Yo"},
};
var configurationBuilder = new ConfigurationBuilder();
configurationBuilder.AddInMemoryCollection(dic);
var config = configurationBuilder.Build();
var options = config.Get<ConfigurationInterfaceOptions>();
var childOptions = options.Section.Get<DerivedOptions>(binderOptions =>
binderOptions.BindPropertyUsingAttributeNames = true);
Assert.Equal("Yo", childOptions.NamedProperty);
}Alternative Designs
Alternative is to use private properties that act as a setter for the desired properties that have the same matching name from JSON. The period in the name doesn't help in my case.
Risks
Existing behavior is preserved. New property to attempt to bind using custom property names is an opt-in behavior. Input or property info sanitation checks would be needed to ensure no binding lookup causes any unexpected exceptions.
Activity
Dotnet-GitSync-Bot commentedon May 7, 2020
I couldn't figure out the best area label to add to this issue. Please help me learn by adding exactly one area label.
Coderrob commentedon Jul 27, 2020
@maryamariyan Originally opened a PR in the dotnet/extensions repo for this work. Not sure if that helps. Applied DataMember attribute property info lookup to support custom data binding names agnostic of Xml/Json specific uses from the extensions internal configuration dictionary.
dotnet/extensions#2810
maryamariyan commentedon Jul 27, 2020
Thanks @Coderrob were you planning on moving over the diff to runtime repo and opening a PR against this new repo instead?
Coderrob commentedon Jul 30, 2020
Sure, I’ll see what I can do this weekend. I found that ability to be incredibly useful in binding. We’ll see what happens.
maryamariyan commentedon Aug 11, 2020
@Coderrob thanks I saw the update on the PR. But as discussed in the PR the best next step on this would be to prepare the API proposal, usage, etc. in the issue page here (following https://github.com/dotnet/runtime/blob/master/docs/project/api-review-process.md).
Since usually API reviews might take a little churn you might end up wanting to close the PR at some point and reopen once this issue gets API approved.
Coderrob commentedon Aug 11, 2020
@maryamariyan updated this issue per the API proposal template.
Coderrob commentedon Aug 12, 2020
Thank you for the help @maryamariyan :)
13 remaining items
SomeoneIsWorking commentedon Mar 18, 2021
The fact that this doesn't exist already is really making me confused
Coderrob commentedon Mar 20, 2021
@safern is this attribute still being considered for implementation? Don’t know if I should do anything else for it.
davidfowl commentedon Mar 22, 2021
@safern Seems threre's nothing that hits the mark besides DisplayName (and that's wrong). I guess we can go with the original proposal.
safern commentedon Mar 22, 2021
Thanks @davidfowl -- I'll set it as ready for review.
terrajobst commentedon Mar 26, 2021
Video
Coderrob commentedon Apr 13, 2021
New binding support implemented. Closing issue.