Skip to content

Configuration binding ignores TypeConverter when binding against a IConfigurationSection #105195

Open
@rchoffardet

Description

@rchoffardet

Description

When binding configuration, it's normally possible to override the conversion by adding a TypeConverterAttribute attribute to the field, property, or class declaration. It does work when binding against a string value but not against a IConfigurationSection.

Reproduction Steps

https://dotnetfiddle.net/gxB9o3

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;


var configuration = new ConfigurationBuilder()
    .AddInMemoryCollection(new Dictionary<string, string>()
    {
        { "0", "Hello"},
        { "1", "world"},
    })
    .Build();

try
{
    var options = configuration.Get<Item>();
    Console.WriteLine("Binding success.");
}
catch (Exception e)
{
    Console.WriteLine("Binding failure.");
}

[TypeConverter(typeof(ItemConverter))]
class Item
{
    private string Zero;
    private string One;

    public Item(string zero, string one)
    {
        Zero = zero;
        One = one;
    }
}

class ItemConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
    {
        return sourceType == typeof(IConfigurationSection);
    }

    public override object ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
    {
        var section = (IConfigurationSection)value;
        return new Item(section.GetValue<string>("0"), section.GetValue<string>("1"));
    }
}

Expected behavior

Item is correctly bound

Actual behavior

Failing this message: "Cannot create instance of type 'Item' because one or more parameters cannot be bound to. Constructor parameters must have corresponding properties. Fields are not supported. Missing properties are: 'zero,one'"

Regression?

Not that I know of

Known Workarounds

None that I know of

Configuration

  • Runtime: .NET 8.0.5
  • OS: Windows 11 Version 23H2
  • Architecture: x64
    It's probably not specific to that configuration, AFAIK, it's the same behavior in .NET 9 preview versions

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions