Populate IConfiguration for unit tests

前端 未结 5 815
别那么骄傲
别那么骄傲 2021-01-17 07:37

.NET Core configuration allows so many options to add values (environment variables, json files, command line args).

I just can\'t figure out and find an answer how

5条回答
  •  梦谈多话
    2021-01-17 08:24

    You can use MemoryConfigurationBuilderExtensions to provide it via a dictionary.

    using Microsoft.Extensions.Configuration;
    
    var myConfiguration = new Dictionary
    {
        {"Key1", "Value1"},
        {"Nested:Key1", "NestedValue1"},
        {"Nested:Key2", "NestedValue2"}
    };
    
    var configuration = new ConfigurationBuilder()
        .AddInMemoryCollection(myConfiguration)
        .Build();
    

    The equivalent JSON would be:

    {
      "Key1": "Value1",
      "Nested": {
        "Key1": "NestedValue1",
        "Key2": "NestedValue2"
      }
    }
    

    The equivalent Environment Variables would be (assuming no prefix / case insensitive):

    Key1=Value1
    Nested__Key1=NestedValue1
    Nested__Key2=NestedValue2
    

提交回复
热议问题