尝试调用 IConfiguration.Get() 时,结果始终为 null

When trying to call IConfiguration.Get() the result is always null

我在尝试使用 IConfiguration 时遇到了一个奇怪的问题。 我的代码如下:

public class testconfigtests
{
    public void DoTest()
    {            
        var testClass = new TestClass()
        {
            Name = "hello"                
        };

        var config = new Dictionary<string, string>()
        {
            { "Section1:section2",  JsonSerializer.Serialize(testClass) }
        };

        var configuration = new ConfigurationBuilder()
            .AddInMemoryCollection(config)
            .Build();

        var testConfig = new GetTestClassConfig<TestClass>();
        var c = testConfig.GetTestAsync(configuration);
        // c is always null
    }
}

public class TestClass
{
    public string Name { get; set; }
}

public class GetTestClassConfig<T>
{
    public T GetTestAsync(IConfiguration configuration)
    {
        var section = configuration.GetSection("Section1:section2");
        return section.Get<T>();
    }

}

我遇到的问题是 result 总是空的。我的理解是 config.Get<> 将 return 是 class 的序列化版本,但它只是 return 为 null。

当您使用 AddInMemoryCollection 时,它不使用任何 JSON 反序列化。 顾名思义,它只是一个集合。 看你用的时候配置的结构是什么样子的。

现在比较一下实际使用支持从JSON构建的方法时配置的结构。

public class Program
{
    static void Main(string[] args)
    {
        var testClass = new TestClass()
        {
            Name = "hello"          
        };

        var configJson = new Dictionary<string, object>()
        {
            { "Section1:section2", testClass }
        };

        var configurationJson = new ConfigurationBuilder()
            .AddJsonStream(new MemoryStream(Encoding.ASCII.GetBytes(JsonSerializer.Serialize(configJson))))
            .Build();

        var testConfig = new GetTestClassConfig<TestClass>();
        var c = testConfig.GetTestAsync(configurationJson);
        
        Console.WriteLine("Result: " + c.Name);
    }
}

public class TestClass
{
    public string Name { get; set; }
}

public class GetTestClassConfig<T>
{
    public T GetTestAsync(IConfiguration configuration)
    {
        IConfigurationSection section = configuration.GetSection("Section1:section2");
        return section.Get<T>();
    }

}

如您所见,配置结构现在实际上包含带有来自 class 字段的键。