【问题标题】:.Net Core - IConfigurationRoot read entire json file.Net Core - IConfigurationRoot 读取整个 json 文件
【发布时间】:2019-07-21 18:07:13
【问题描述】:

我有以下 Config.jsonfile

{
   "UserId": 2930,
   "Phones":["<HomePhoneNumber>", "<MobileNumber>"]
}

而且我在 Config.cs 中有对应的 Config 类

public class Config
{
  public int UserId { get; set; }
  public List<string> Phones { get; set;}
}

我正在关注本教程 - https://keestalkstech.com/2018/04/dependency-injection-with-ioptions-in-console-apps-in-net-core-2/

但我的 config.json 文件中没有像他的 appsettings.json 这样的部分。我想整体阅读该配置文件。如何使用 ConfigurationBuilder 做到这一点?

class Program
{
    static async Task Main(string[] args)
    {
        var services = new ServiceCollection();
        ConfigureServices(services);
        var serviceProvider = services.BuildServiceProvider();

        var config = serviceProvider.GetService<Config>();
    }

    private static void ConfigureServices(IServiceCollection services)
    {
        services.AddLogging(builder => builder.AddDebug().AddConsole());

        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("Config.json", false)
            .Build();

        services.AddOptions();
        services.Configure<Config>(configuration);
    }
}

【问题讨论】:

    标签: c# dependency-injection configuration .net-core


    【解决方案1】:

    由于选项配置,您需要通过IOptions 访问它

    //...
    
    var serviceProvider = services.BuildServiceProvider();
    var option = serviceProvider.GetService<IOptions<Config>>();
    var config = option.Value;
    

    另一种方法是直接从配置中提取类,方法是绑定到所需的对象图,然后将其添加到服务集合中

    //...
    
    var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("Config.json", false)
        .Build();
    
    var config = configuration.Get<Config>();
    services.AddSingleton(config);
    
    //...
    

    用上面的方法

    //...
    
    var config = serviceProvider.GetService<Config>();
    

    将按预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-18
      • 2023-03-12
      • 1970-01-01
      • 2021-04-09
      • 2022-01-09
      • 2016-03-09
      • 1970-01-01
      • 2015-08-19
      相关资源
      最近更新 更多