如何使用 .NET Core 从控制台应用程序中的 appsettings.json 获取值? [英] How to get values from appsettings.json in a console application using .NET Core?
问题描述
我正在使用 .NET Core 3.1 创建一个控制台应用程序,我想要一个 appsettings json 来加载所有environment、paths、variables、...在执行开始时,然后从其他库类中获取值.我已经使用 appsettings json 中包含的数据创建了一个设置"类.这是我在教程中已经看到的,但我无法获得任何价值.
i'm creating a console application using .NET Core 3.1 and i would like to have an appsettings json to load all environment, paths, variables,... at the beginning of the execution, and then get values from other library classes. I have created a 'Settings' class with the data included in the appsettings json. This is what i have already by looking out in tutorials but i'm not able to get any value.
//Start.cs
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
}
//Settings.cs
public class Settings
{
public ConnectionStrings ConnectionStrings { get; set; }
public Logging Logging { get; set; }
public AppSettings AppSettings { get; set; }
...
//A class to use it in other lib
public class Extractor
{
private readonly IConfiguration _configuration;
public Extractor(IConfiguration configuration) : this()
{
_configuration = configuration;
Init();
}
public void Init()
{
// Extractor:Min is a variable included in appsettings.json
Min = _configuration.GetValue<int>("Extractor:Min")
}
我无法制作正确的 Main 因为我不知道如何初始化所有内容...我错过了什么?我想我一直在绕圈子做这么简单的事情.提前致谢!注意:我需要从另一个库类中获取这些变量,而不是在 Main 中.我不知道如何在其他类中初始化配置"以使用它.谢谢
I cannot make a proper Main as i don't know how to initialize everything...what am i missing? I think i've been going in circles for something that easy. Thanks in advance! NOTE: i need to get those variables from another library class, not in Main. I don't know how to initialize 'configuration' in other classes in order to use it. Thanks
推荐答案
您的示例混合了一些希望托管您的代码的 ASP NET Core 方法.要最低限度地解决从 JSON 配置获取选项或设置的问题,请考虑以下事项:
Your example is mixing in some ASP NET Core approaches that expect your code to be hosted. To minimally solve the issue of getting options or settings from a JSON configuration, consider the following:
一个 config.json
文件,设置为复制到输出目录";以便它包含在构建中:
A config.json
file, set to "Copy to Output Directory" so that it is included with the build:
{
"MyFirstClass": {
"Option1": "some string value",
"Option2": 42
},
"MySecondClass": {
"SettingOne": "some string value",
"SettingTwo": 42
}
}
以下方法将从 JSON 文件加载内容,然后将内容绑定到两个强类型选项/设置类,这比逐个值要干净得多:
The following approach will load the content from the JSON file, then bind the content to two strongly-typed options/settings classes, which can be a lot cleaner than going value-by-value:
using System;
using System.IO;
using Microsoft.Extensions.Configuration;
// NuGet packages:
// Microsoft.Extensions.Configuration.Binder
// Microsoft.Extensions.Configuration.Json
namespace SampleConsole
{
class Program
{
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("config.json", optional: false);
IConfiguration config = builder.Build();
var myFirstClass = config.GetSection("MyFirstClass").Get<MyFirstClass>();
var mySecondClass = config.GetSection("MySecondClass").Get<MySecondClass>();
Console.WriteLine($"The answer is always {myFirstClass.Option2}");
}
}
public class MyFirstClass
{
public string Option1 { get; set; }
public int Option2 { get; set; }
}
public class MySecondClass
{
public string SettingOne { get; set; }
public int SettingTwo { get; set; }
}
}
这篇关于如何使用 .NET Core 从控制台应用程序中的 appsettings.json 获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!