使用.NET Core Microsoft.Extensions.Configuration 是否可以将Configuration绑定到包含数组的对象?
ConfigurationBinder有一个方法BindArray,所以我认为它会工作.
但是当我尝试它时,我得到一个例外:
System.NotSupportedException: ArrayConverter cannot convert from System.String.
这是我精简的代码:
public class Test
{
private class ExampleOption
{
public int[] Array {get;set;}
}
[Test]
public void CanBindArray()
{
// ARRANGE
var config =
new ConfigurationBuilder()
.AddInMemoryCollection(new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("Array", "[1,2,3]")
})
.Build();
var exampleOption= new ExampleOption();
// ACT
config.Bind(complexOptions); // throws exception
// ASSERT
exampleOption.ShouldContain(1);
}
}
Run Code Online (Sandbox Code Playgroud) 我在config.json文件中有一个如下列表
{
"foo": {
"bar": [
"1",
"2",
"3"
]
}
}`
Run Code Online (Sandbox Code Playgroud)
我可以使用以下命令在运行时获取列表
Configuration.GetSection("foo:bar").Get<List<string>>()
Run Code Online (Sandbox Code Playgroud)
我想模拟configuration.GetSection编写单元测试。
以下语法失败
mockConfigRepo
.SetupGet(x => x.GetSection("reportLanguageSettings:reportLanguageList").Get<List<string>>())
.Returns(reportLanguages);
Run Code Online (Sandbox Code Playgroud)