问题描述
我正在将一个应用程序移植到依赖于 .settings
文件的 .NET 核心.不幸的是,我找不到从 .NET 核心读取它的方法.通常,将以下几行添加到 .csproj
会生成一个 TestSettings
类,让我可以读取设置.
I'm porting an application to .NET core which relies on a .settings
file. Unfortunately, I can't find a way to read it from .NET core. Normally, adding the following lines to the .csproj
would generate a TestSettings
class that would let me read the settings.
<ItemGroup>
<None Include="TestSettings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
</None>
</ItemGroup>
不幸的是,这似乎不再起作用.我什至无法验证 SettingsSingleFileGenerator
是否运行.此 GitHub 问题 表明这是新 .csproj 的错误code> 格式,但没有人提供替代方案.
Unfortunately, this no longer seems to do anything. I can't even verify that the
SettingsSingleFileGenerator
runs at all. This GitHub issue suggests that this is a bug with the new .csproj
format, but no one has offered an alternative.
在 .NET core 中读取
.settings
文件的正确方法是什么?
What is the proper way of reading
.settings
files in .NET core?
推荐答案
对于 .NET Core 2.x,使用
Microsoft.Extensions.Configuration
命名空间(见下面的注释),还有很多NuGet 上的许多扩展,你会想要从环境变量到 Azure Key Vault(但更现实地,JSON 文件、XML 等)的源中读取.
For .NET Core 2.x, use the
Microsoft.Extensions.Configuration
namespace (see note below), and there are tons of extensions on NuGet you'll want to grab for reading from sources ranging from environment variables to Azure Key Vault (but more realistically, JSON files, XML, etc).
以下是控制台程序中的一个示例,该程序检索设置的方式与我们在为 Azure 站点启动 Kestrel 时使用它们的方式相同:
Here's an example from a console program that retrieves settings the same way we use them when Kestrel starts up for our Azure sites:
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
// This allows us to set a system environment variable to Development
// when running a compiled Release build on a local workstation, so we don't
// have to alter our real production appsettings file for compiled-local-test.
//.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
.AddEnvironmentVariables()
//.AddAzureKeyVault()
.Build();
然后在需要设置的代码中,您只需引用
Configuration
或注册 IConfiguration
以进行依赖注入或其他任何操作.
Then in your code that needs settings, you just reference
Configuration
or you register IConfiguration
for dependency injection or whatever.
注意:
IConfiguration
是只读的,根据 此 评论.因此,如果需要阅读和写作,您将需要不同的选择.可能是 System.Configuration
sans 设计师.
Note:
IConfiguration
is read-only and will likely never get persistence per this comment. So if reading AND writing are required, you'll need a different option. Probably System.Configuration
sans designer.
这篇关于如何在 .NET Core 中使用 .settings 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!