你的问题是Microsoft.Extensions.Configuration.Binder
does not use System.Text.Json to deserialize JSON.相反,它手动将JSON解析为IConfigurationSection
个元素,然后使用反射将这些元素绑定到POCO.所有这些似乎都没有记录在案,所以为了确认,你可以判断source code for ConfigurationBinder
.
在.NET 6中,方法BindDictionary()
用于绑定到词典.它对字典键类型的注释限制为string
和枚举类型:
private static void BindDictionary(
object dictionary,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
Type dictionaryType,
IConfiguration config, BinderOptions options)
{
// IDictionary<K,V> is guaranteed to have exactly two parameters
Type keyType = dictionaryType.GenericTypeArguments[0];
Type valueType = dictionaryType.GenericTypeArguments[1];
bool keyTypeIsEnum = keyType.IsEnum;
if (keyType != typeof(string) && !keyTypeIsEnum)
{
// We only support string and enum keys
return;
}
在.NET 7中,存在包含明确支持数字键的逻辑(经由PR #71609添加)的附加方法BindDictionaryInterface()
:
private static object? BindDictionaryInterface(
object? source,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)]
Type dictionaryType,
IConfiguration config, BinderOptions options)
{
// IDictionary<K,V> is guaranteed to have exactly two parameters
Type keyType = dictionaryType.GenericTypeArguments[0];
Type valueType = dictionaryType.GenericTypeArguments[1];
bool keyTypeIsEnum = keyType.IsEnum;
bool keyTypeIsInteger =
keyType == typeof(sbyte) ||
keyType == typeof(byte) ||
keyType == typeof(short) ||
keyType == typeof(ushort) ||
keyType == typeof(int) ||
keyType == typeof(uint) ||
keyType == typeof(long) ||
keyType == typeof(ulong);
if (keyType != typeof(string) && !keyTypeIsEnum && !keyTypeIsInteger)
{
// We only support string, enum and integer (except nint-IntPtr and nuint-UIntPtr) keys
return null;
}
这解释了为什么只有在迁移到.NET 7后才能成功绑定public Dictionary<int, CategoryMapping> CategoryMappings { get; set; }
属性.
如果您不能迁移到.NET7,但仍然需要使用带有整数键的字典,那么as a workaround您可以使用adapter pattern将您的整数字典包装在IDictionary<string, TValue>
个替代字典中.
首先,定义以下IntegerDictionaryAdapter<TValue>
个类:
public class IntegerDictionaryAdapter<TValue> : AdapterDictionary<int, string, TValue>
{
static int ToInt(string value) => int.Parse(value, NumberFormatInfo.InvariantInfo);
static string ToString(int value) => value.ToString(NumberFormatInfo.InvariantInfo);
public IntegerDictionaryAdapter() : base(new Dictionary<int, TValue>(), s => ToInt(s), i => ToString(i)) { }
public IntegerDictionaryAdapter(IDictionary<int, TValue> dictionary) : base(dictionary, s => ToInt(s), i => ToString(i)) { }
}
public class AdapterDictionary<TKeyIn, TKeyOut, TValue> : IDictionary<TKeyOut, TValue>
{
readonly IDictionary<TKeyIn, TValue> dictionary;
readonly Func<TKeyIn, TKeyOut> mapKeyToOuter;
readonly Func<TKeyOut, TKeyIn> mapKeyToInner;
public AdapterDictionary(IDictionary<TKeyIn, TValue> dictionary, Func<TKeyOut, TKeyIn> mapKeyToInner, Func<TKeyIn, TKeyOut> mapKeyToOuter)
{
this.dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
this.mapKeyToInner = mapKeyToInner ?? throw new ArgumentNullException(nameof(mapKeyToInner));
this.mapKeyToOuter = mapKeyToOuter ?? throw new ArgumentNullException(nameof(mapKeyToOuter));
}
public IDictionary<TKeyIn, TValue> UnderlyingDictionary => dictionary;
KeyValuePair<TKeyIn, TValue> MapItemToOuter(KeyValuePair<TKeyOut, TValue> item) { return new KeyValuePair<TKeyIn, TValue>(mapKeyToInner(item.Key), item.Value); }
KeyValuePair<TKeyOut, TValue> MapItemFromOuter(KeyValuePair<TKeyIn, TValue> item) { return new KeyValuePair<TKeyOut, TValue>(mapKeyToOuter(item.Key), item.Value); }
public void Add(TKeyOut key, TValue value) { dictionary.Add(mapKeyToInner(key), value); }
public bool ContainsKey(TKeyOut key) { return dictionary.ContainsKey(mapKeyToInner(key)); }
public ICollection<TKeyOut> Keys => new CollectionAdapter<TKeyIn, TKeyOut>(() => dictionary.Keys, mapKeyToOuter, mapKeyToInner);
public bool Remove(TKeyOut key) { return dictionary.Remove(mapKeyToInner(key)); }
public bool TryGetValue(TKeyOut key, out TValue value) { return dictionary.TryGetValue(mapKeyToInner(key), out value); }
public ICollection<TValue> Values { get { return dictionary.Values; } }
public TValue this[TKeyOut key]
{
get { return dictionary[mapKeyToInner(key)]; }
set { dictionary[mapKeyToInner(key)] = value; }
}
public void Add(KeyValuePair<TKeyOut, TValue> item) { dictionary.Add(MapItemToOuter(item)); }
public void Clear() { dictionary.Clear(); }
public bool Contains(KeyValuePair<TKeyOut, TValue> item) { return dictionary.Contains(MapItemToOuter(item)); }
public void CopyTo(KeyValuePair<TKeyOut, TValue>[] array, int arrayIndex) => this.CopyToArray(array, arrayIndex);
public int Count { get { return dictionary.Count; } }
public bool IsReadOnly { get { return dictionary.IsReadOnly; } }
public bool Remove(KeyValuePair<TKeyOut, TValue> item) { return dictionary.Remove(MapItemToOuter(item)); }
public IEnumerator<KeyValuePair<TKeyOut, TValue>> GetEnumerator() { return dictionary.Select(i => MapItemFromOuter(i)).GetEnumerator(); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
public abstract class CollectionAdapterBase<TIn, TOut, TCollection> : ICollection<TOut>
where TCollection : ICollection<TIn>
{
readonly Func<TCollection> getCollection;
readonly Func<TIn, TOut> toOuter;
public CollectionAdapterBase(Func<TCollection> getCollection, Func<TIn, TOut> toOuter)
{
this.getCollection = getCollection ?? throw new ArgumentNullException(nameof(getCollection));
this.toOuter = toOuter ?? throw new ArgumentNullException(nameof(toOuter));
}
protected TCollection Collection { get { return getCollection(); } }
protected TOut ToOuter(TIn inner) { return toOuter(inner); }
public abstract void Add(TOut item);
public abstract void Clear();
public virtual bool Contains(TOut item)
{
var comparer = EqualityComparer<TOut>.Default;
foreach (var member in Collection)
if (comparer.Equals(item, ToOuter(member)))
return true;
return false;
}
public void CopyTo(TOut[] array, int arrayIndex) => this.CopyToArray(array, arrayIndex);
public int Count { get { return Collection.Count; } }
public abstract bool IsReadOnly { get; }
public abstract bool Remove(TOut item);
public IEnumerator<TOut> GetEnumerator() => Collection.Select(item => ToOuter(item)).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
public class CollectionAdapter<TIn, TOut> : CollectionAdapterBase<TIn, TOut, ICollection<TIn>>
{
readonly Func<TOut, TIn> toInner;
public CollectionAdapter(Func<ICollection<TIn>> getCollection, Func<TIn, TOut> toOuter, Func<TOut, TIn> toInner)
: base(getCollection, toOuter)
{
this.toInner = toInner ?? throw new ArgumentNullException(nameof(toInner));
}
protected TIn ToInner(TOut outer) { return toInner(outer); }
public override void Add(TOut item) => Collection.Add(ToInner(item));
public override void Clear() => Collection.Clear();
public override bool IsReadOnly { get { return Collection.IsReadOnly; } }
public override bool Remove(TOut item) => Collection.Remove(ToInner(item));
public override bool Contains(TOut item) => Collection.Contains(ToInner(item));
}
public static class EnumerableExtensions
{
internal static void CopyToArray<TItem>(this IEnumerable<TItem> collection, TItem[] array, int arrayIndex)
{
ArgumentNullException.ThrowIfNull(collection);
ArgumentNullException.ThrowIfNull(array);
foreach (var item in collection)
array[arrayIndex++] = item;
}
}
然后修改您的类以使用它,如下所示:
public class Sender {
public string SenderID { get; set; }
public string FeedType { get; set; }
public IntegerDictionaryAdapter<CategoryMapping> CategoryMappings { get; set; } = new();
}
public class CategoryMapping {
public int CategoryID { get; set; }
public string VccCategoryName { get; set; }
public string ReiCategoryName { get; set; }
public IntegerDictionaryAdapter<CategoryMapping> SubcategoryMappings { get; set; } = new();
}
public class SubcategoryMapping
{
public int SubcategoryID { get; set; }
public int ParentCategoryID { get; set; }
public string VccSubcategoryName { get; set; }
public string ReiSubcategoryName { get; set; }
}
现在,您将能够在.NET 6(以及.NET 7)中绑定您的配置数据模型,如下所示,使用UnderlyingDictionary
属性访问您的整数键词典:
List<Sender> people = Configuration.GetSection("TestMap").Get<List<Sender>>();
people.First().CategoryMappings.UnderlyingDictionary.Add(10101, new CategoryMapping { CategoryID = 10101, VccCategoryName = "foo", ReiCategoryName = "bar" });
(然而,老实说,我不确定是否值得这么麻烦.)
演示小提琴here.