在.Net Core中使用app.config
我有问题。 我需要在.Net Core(C#)中编写一个使用app.config的程序,如下所示:
我写道:
string connectionString = ConfigurationManager.ConnectionStrings["sampleDatabase"].ConnectionString; Console.WriteLine(connectionString); // read appSettings configuration string appSettingValue = ConfigurationManager.AppSettings["sampleApplication"]; Console.WriteLine(appSettingValue);
它是来自互联网的例子,所以我认为会工作,但我得到例外:
System.Configuration.ConfigurationErrorsException: 'Error Initializing the configuration system.' Inner Exception TypeLoadException: Could not load type 'System.Configuration.InternalConfigurationHost' from assembly 'CoreCompat.System.Configuration, Version=4.2.3.0, Culture=neutral, PublicKeyToken=null' because the method 'get_bundled_machine_config' has no implementation (no RVA).
我通过NuGet下载 – 安装 – 包CoreCompat.System.Configuration -Version 4.2.3-r4 -Pre仍然无法正常工作。 也许有人可以帮助我?
-
您可以将Configuration API与任何 .NET Core应用程序配合使用,而不仅仅是ASP.NET Core应用程序。 查看链接中提供的示例,其中显示了如何在控制台应用程序中读取配置。
-
在大多数情况下,JSON源(读作
.json
文件)是最合适的配置源。注意:当有人说配置文件应该是
appsettings.json
时,不要混淆。 您可以使用任何适合您的文件名,文件位置可能不同 – 没有具体规则。但是,由于现实世界很复杂,因此有很多不同的配置提供商:
- 文件格式(INI,JSON和XML)
- 命令行参数
- 环境变量
等等。 您甚至可以使用/编写自定义提供程序。
-
实际上,
app.config
配置文件是一个XML文件。 因此,您可以使用XML配置提供程序( github上的源代码 , nuget链接 )从中读取设置。 但请记住,它仅用作配置源 – 您的应用程序行为应该由您实现。 配置提供程序不会更改“设置”并为您的应用设置策略,而只会从文件中读取数据。
即使在Linux上的.NET Core 2.0中,也可以使用常用的System.Configuration
。 试试这个测试示例:
- 创建了.NET Standard 2.0库(比如
MyLib.dll
) - 添加了NuGet包
System.Configuration.ConfigurationManager
v4.4.0。 这是必需的,因为这个包不包含在元包NetStandard.Library
(我希望改变) - 从
ConfigurationSection
或ConfigurationElement
派生的所有C#类都进入MyLib.dll
。 例如,MyClass.cs
派生自ConfigurationSection
,MyAccount.cs
派生自ConfigurationElement
。 实施细节不在此范围,但Google是您的朋友 - 创建.NET Core 2.0应用程序(例如控制台应用程序,
MyApp.dll
)。 .NET Core应用程序以.dll
而不是Framework中的.exe
结尾。 - 使用自定义配置部分在
MyApp
创建app.config
。 这显然应该与上面#3中的class级设计相匹配。 例如:
就是这样 – 你会发现app.config在MyApp
正确解析,你MyLib
的现有代码工作得很好。 如果您将平台从Windows(dev)切换到Linux(测试),请不要忘记运行dotnet restore
。