[英].Net Core - IConfigurationRoot read entire json file
I have following Config.jsonfile 我有以下Config.jsonfile
{
"UserId": 2930,
"Phones":["<HomePhoneNumber>", "<MobileNumber>"]
}
And I have corresponding Config class in Config.cs 我在Config.cs中有对应的Config类
public class Config
{
public int UserId { get; set; }
public List<string> Phones { get; set;}
}
I was following this tutorial - https://keestalkstech.com/2018/04/dependency-injection-with-ioptions-in-console-apps-in-net-core-2/ 我正在关注本教程-https: //keestalkstech.com/2018/04/dependency-injection-with-ioptions-in-console-apps-in-net-core-2/
But I don't have sections like his appsettings.json in my config.json file. 但是我的config.json文件中没有像他的appsettings.json这样的部分。 I want to read that config file as a whole.
我想整体读取该配置文件。 How can I do that with ConfigurationBuilder?
如何使用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);
}
}
Because of options configuration you would need to access it via IOptions
由于选项配置,您需要通过
IOptions
访问它
//...
var serviceProvider = services.BuildServiceProvider();
var option = serviceProvider.GetService<IOptions<Config>>();
var config = option.Value;
another approach would be to extract the class directly from configuration by binding to the desired object graph and then adding it to the service collection 另一种方法是通过绑定到所需的对象图直接从配置中提取类,然后将其添加到服务集合中
//...
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("Config.json", false)
.Build();
var config = configuration.Get<Config>();
services.AddSingleton(config);
//...
With the above approach 用以上方法
//...
var config = serviceProvider.GetService<Config>();
will work as expected. 将按预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.