.Net Core-IConfigurationRoot读取整个json文件

时间:2019-02-27 22:11:01

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

我有以下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);
    }
}

1 个答案:

答案 0 :(得分:0)

由于选项配置,您需要通过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>();

将按预期工作。