【问题标题】:.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
- 将设置添加到您的 appsettings.json:“setting1”:“测试设置”。
- 创建一个类:
public class AppSettings
{
public string Setting1 { get; set; }
}
- 将
services.Configure<AppSettings>(Configuration); 添加到您的startup.cs
- 现在您可以在需要这些选项的类中注入
IOptions<AppSettings> appSettings