【问题标题】:Read appsettings.json keys in methods other than Main Program.cs .NetCore 3.1 console app在 Main Program.cs .NetCore 3.1 控制台应用程序以外的方法中读取 appsettings.json 键
【发布时间】:2020-10-28 12:52:19
【问题描述】:

基本上我必须从 .netcore 控制台应用程序调用 REST API,它会返回一些 xml,然后这个控制台应用程序需要从该 xml 创建一个 csv 文件。 我需要在我的 appsettings.config 中保留 REST API url 和 csv 路径。 我为此创建了两个密钥。

现在我不想在我的 main 方法中读取这些键,但我正在我的 main 方法中构建 ConfigurationBuilder,因此它仅在 Main 方法中可用。 我的 Main 方法中的代码如下所示。

 configuration = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", true, true)
.AddEnvironmentVariables()
 .Build();

其中配置是 Program.cs 类级别的 static IConfiguation configuration = null。 现在我已经将此 ConfigurationBuilder 作为类级别的静态变量,在 Main 中对其进行初始化,然后在其他地方读取它,但不确定它是否是一种好方法或有更好的方法来做到这一点? 任何建议将不胜感激。

【问题讨论】:

  • 一个好的方法可能是依赖注入,不幸的是你在一个控制台应用程序中,但它仍然很容易设置(andrewlock.net/…)。然后你可以注册你的IConfiguration,从现在开始它就可以在需要它的类的构造函数中使用了。更好的方法是遵循选项模式。

标签: .net-core console-application appsettings


【解决方案1】:

在我看来,您应该使用 @Marco Luzzaras 评论中描述的依赖注入。

但如果在您的情况下不可能,您也可以通过将所有内容封装在 Singleton 中来访问相同的配置

public class ConfigurationProvider 
{
    private static IConfiguration _instance;
    public static IConfiguration Instance 
    {
        get 
        {
            if(_instance == null)
            {
                _instance = new ConfigurationBuilder()
                    .AddJsonFile($"appsettings.json", optional: true)
                    .AddEnvironmentVariables()
                    .Build();
            }
            return _instance;
        }
    }
}

...并在您需要的任何地方使用它。

dotnet fiddle Example

【讨论】:

  • 感谢所有花时间回答的人:)
猜你喜欢
  • 2017-06-03
  • 2022-08-02
  • 2022-12-12
  • 2019-11-19
  • 2018-04-06
  • 2020-07-14
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多