Skip to content

Configuration > Binder - Support for binding by custom attribute names.  #36010

Closed

Description

@Coderrob

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

  1. Dotnet-GitSync-Bot commented on May 7, 2020

    @Dotnet-GitSync-Bot
    Collaborator

    I couldn't figure out the best area label to add to this issue. Please help me learn by adding exactly one area label.

  2. added
    untriaged
    on May 7, 2020
  3. added this to the Future milestone on May 7, 2020
  4. removed
    untriaged
    on Jul 1, 2020
  5. Coderrob commented on Jul 27, 2020

    @Coderrob
    ContributorAuthor

    @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

  6. maryamariyan commented on Jul 27, 2020

    @maryamariyan
    Contributor

    Thanks @Coderrob were you planning on moving over the diff to runtime repo and opening a PR against this new repo instead?

  7. Coderrob commented on Jul 30, 2020

    @Coderrob
    ContributorAuthor

    Thanks @Coderrob were you planning on moving over the diff to runtime repo and opening a PR against this new repo instead?

    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.

  8. maryamariyan commented on Aug 11, 2020

    @maryamariyan
    Contributor

    @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.

  9. Coderrob commented on Aug 11, 2020

    @Coderrob
    ContributorAuthor

    @maryamariyan updated this issue per the API proposal template.

  10. modified the milestones: Future, 6.0.0 on Aug 11, 2020
  11. Coderrob commented on Aug 12, 2020

    @Coderrob
    ContributorAuthor

    Thank you for the help @maryamariyan :)

  12. 13 remaining items

  13. SomeoneIsWorking commented on Mar 18, 2021

    @SomeoneIsWorking

    The fact that this doesn't exist already is really making me confused

  14. Coderrob commented on Mar 20, 2021

    @Coderrob
    ContributorAuthor

    @safern is this attribute still being considered for implementation? Don’t know if I should do anything else for it.

  15. davidfowl commented on Mar 22, 2021

    @davidfowl
    Member

    @safern Seems threre's nothing that hits the mark besides DisplayName (and that's wrong). I guess we can go with the original proposal.

  16. safern commented on Mar 22, 2021

    @safern
    Member

    Thanks @davidfowl -- I'll set it as ready for review.

  17. added
    api-ready-for-review
    and removed
    api-suggestion
    on Mar 22, 2021
  18. added
    api-approved
    and removed
    api-ready-for-review
    on Mar 26, 2021
  19. terrajobst commented on Mar 26, 2021

    @terrajobst
    Contributor

    Video

    • Looks good as proposed
      • Does this need an analyzer?
    namespace Microsoft.Extensions.Configuration
    {
        [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
        public sealed class ConfigurationKeyNameAttribute : Attribute
        {
            public ConfigurationKeyNameAttribute(string name);
            public string Name { get; }
        }
    }
  20. added
    help wanted
    on Mar 26, 2021
  21. Coderrob commented on Apr 13, 2021

    @Coderrob
    ContributorAuthor

    New binding support implemented. Closing issue.

  22. ghost locked as resolved and limited conversation to collaborators on May 13, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-Extensions-Configurationfeature-requesthelp wanted

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions