【问题标题】:.NET Core Settings - the best practice [closed].NET Core 设置 - 最佳实践 [关闭]
【发布时间】:2020-02-05 14:07:45
【问题描述】:

在 .NET Framework 中,我习惯于使用属性 - 设置 (Properties.Settings.Default.SomeSettingsValue) 中的设置。使用起来非常简单和干净。我现在开始使用 .NET Core,但是没有这样的设置。我找到了一些解决方案,但没有一个像旧的那样干净简单。

.NET Core 中设置的最佳实践和解决方案是什么?

谢谢。

【问题讨论】:

    标签: c# .net asp.net-core .net-core configuration


    【解决方案1】:

    您应该使用ASP.Net Core Configuration API。例如,您可以将配置设置添加到 appsettings.json 文件中,该文件通常会在您首次创建项目时自动添加到您的项目中,例如:

    {
        "Logging": {
            "LogLevel": {
                "Default": "Information"
            }
        },
        "ConnectionStrings": {
            "MyDatabase": "Server=Server1;Database=MyDatabase;Integrated Security=false;",
        },
    }
    

    【讨论】:

      【解决方案2】:

      我想你正在寻找Options pattern

      1. 将设置添加到您的 appsettings.json:“setting1”:“测试设置”。
      2. 创建一个类: public class AppSettings {
        public string Setting1 { get; set; } }
      3. 将services.Configure<AppSettings>(Configuration); 添加到您的startup.cs
      4. 现在您可以在需要这些选项的类中注入 IOptions<AppSettings> appSettings

      【讨论】:

      • 控制台应用怎么样?
      • 我不知道,但我找到了this。希望对您有所帮助!
      猜你喜欢
      • 2010-10-06
      • 2018-04-27
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 2020-09-17
      • 2013-10-02
      相关资源
      最近更新 更多