-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Closed
Description
Is there an existing issue for this?
- I have searched the existing issues
Describe the bug
Only .NET 7.0.1, .NET 6 and .NET 7.0.0 work well.
When I use a Collection in appsettings.json
And use builder.Services.BuildServiceProvider().CreateScope()
scope.ServiceProvider.GetService
to read the config I registered.
It will throw an exception: System.Reflection.AmbiguousMatchException:“Ambiguous match found.”
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"MyRootSetting": {
"Key1": "aaa",
/*This "Items" will lead to errors.*/
"Items": {
"A1": {
"Key1": "bbb"
}
}
}
}
Setting classes
namespace WebApplication1;
public class MyRootSetting : MySettingItem
{
public string? TopKey { get; set; }
public MySettingItemCollection? Items { get; set; }
public MySettingItem this[string key]
{
get => Items[key];
set => Items[key] = value;
}
}
public class MySettingItem
{
public string? Key1 { get; set; }
}
public class MySettingItemCollection : Dictionary<string, MySettingItem>
{
public new MySettingItem this[string key]
{
get
{
if (!base.ContainsKey(key))
{
base[key] = new MySettingItem();
}
return base[key];
}
set
{
base[key] = value;
base[key].Key1 = key;
}
}
}
Program.cs
using Microsoft.Extensions.Options;
using WebApplication1;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.Configure<MyRootSetting>(builder.Configuration.GetSection("MyRootSetting"));
using (var scope = builder.Services.BuildServiceProvider().CreateScope())
{
// this line will throw an exception
var setting = scope.ServiceProvider.GetService<IOptions<MyRootSetting>>().Value;
Console.WriteLine(setting.TopKey);
Console.WriteLine(setting.Items.FirstOrDefault().Value.Key1);
}
var app = builder.Build();
app.UseAuthorization();
app.MapControllers();
app.Run();
Source Code
Expected Behavior
No error is reported, and Items can be read normally.
Or a more specific exception.
Steps To Reproduce
Download the source code and make sure it is released by .net 7.0.1 (2022-12-13). If run it directly, will report an error.
Exceptions (if any)
System.Reflection.AmbiguousMatchException: “Ambiguous match found.”
.NET Version
7.0.101
Anything else?
Visual Studio 2022 (v17.4.3)
Other
Docker : mcr.microsoft.com/dotnet/aspnet:7.0.1