繁体   English   中英

在 .Net Core 中使用 app.config

[英]Using app.config in .Net Core

我有问题。 我需要在 .Net Core(C#) 中编写一个程序,它使用 app.config,如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="custom" type="ConfigurationSample.CustomConfigurationSection, ConfigurationSample"/>
  </configSections>
  <connectionStrings>
    <add name="sampleDatabase" connectionString="Data Source=localhost\SQLExpress;Initial Catalog=SampleDatabase;Integrated Security=True"/>
  </connectionStrings>
  <appSettings>
    <add key="sampleApplication" value="Configuration Sample"/>
  </appSettings>
  <custom>
    <customConfigurations>
      <add key="customSample" name="Mickey Mouse" age="83"/>
    </customConfigurations>
  </custom>
</configuration>

我写:

string connectionString = ConfigurationManager.ConnectionStrings["sampleDatabase"].ConnectionString;
Console.WriteLine(connectionString);

// read appSettings configuration
string appSettingValue = ConfigurationManager.AppSettings["sampleApplication"];
Console.WriteLine(appSettingValue);

它是来自 inte.net 的示例,所以我认为可行,但我遇到了例外情况:

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 - Install-Package CoreCompat.System.Configuration -Version 4.2.3-r4 -Pre 下载但仍然无法正常工作。 也许有人可以帮助我?

即使在 Linux 上的 .NET Core 2.0 中,也可以使用您常用的System.Configuration 试试这个测试示例:

  1. 创建了一个 .NET Standard 2.0 库(比如MyLib.dll
  2. 添加了 NuGet 包System.Configuration.ConfigurationManager v4.4.0。 这是必需的,因为元包NetStandard.Library未涵盖此包(我希望有所改变)
  3. ConfigurationSectionConfigurationElement派生的所有 C# 类都进入MyLib.dll 例如, MyClass.cs派生自ConfigurationSection ,而MyAccount.cs派生自ConfigurationElement 实施细节超出了此处的范围,但Google 是您的朋友
  4. 创建 .NET Core 2.0 应用程序(例如控制台应用程序MyApp.dll )。 .NET Core 应用程序以.dll而不是 Framework 中的.exe结尾。
  5. 使用您的自定义配置部分在MyApp中创建一个app.config 这显然应该与上面#3 中的类设计相匹配。 例如:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
  </configSections>
  <myCustomConfig>
    <myAccount id="007" />
  </myCustomConfig>
</configuration>

就是这样 - 您会发现 app.config 在MyApp中被正确解析,并且您在MyLib中的现有代码工作得很好。 如果将平台从 Windows (dev) 切换到 Linux (test),请不要忘记运行dotnet restore

此外,app.config 在运行时的位置不同于 .net 框架中的位置,而不是“projectName.exe.config”。 它现在是 .net 核心中的“projectName.dll.config”。

测试项目的其他解决方法

如果您发现您的App.config在您的测试项目中不起作用,您可能需要在您的测试项目的.csproj中使用此代码段(例如,就在结尾</Project>之前)。 它基本上将App.config作为testhost.dll.config复制到您的输出文件夹中,以便dotnet test将其拾取。

  <!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
  <Target Name="CopyCustomContent" AfterTargets="AfterBuild">
    <Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
  </Target>
  <!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
  1. 您可以将Microsoft.Extensions.Configuration API任何.NET Core 应用程序一起使用,而不仅仅是与 ASP.NET Core 应用程序一起使用。 查看链接中提供的示例,它显示了如何在控制台应用程序中读取配置。

  2. 在大多数情况下,JSON 源(读取为.json文件)是最合适的配置源。

    注意:当有人说配置文件应该是appsettings.json时,请不要感到困惑。 您可以使用任何适合您的文件名,文件位置可能不同——没有特定规则。

    但是,由于现实世界很复杂,所以有很多不同的配置提供程序:

    • 文件格式(INI、JSON 和 XML)
    • 命令行参数
    • 环境变量

    等等。 您甚至可以使用/编写自定义提供程序。

  3. 实际上, app.config配置文件是一个 XML 文件。 因此,您可以使用 XML 配置提供程序( github 上的源代码nuget 链接)从中读取设置。 但请记住,它将仅用作配置源 - 您的应用程序行为方式的任何逻辑都应由您实现。 Configuration Provider 不会更改“设置”并为您的应用设置策略,而只会从文件中读取数据。

我有一个具有类似问题的 .Net Core 3.1 MSTest 项目。 这篇文章提供了修复它的线索。

将其分解为 .Net core 3.1 的简单答案:

  • 添加/确保 nuget 包:System.Configuration.ConfigurationManager 到项目
  • 将您的 app.config(xml) 添加到项目中。

如果是 MSTest 项目:

  • 将项目中的文件重命名为 testhost.dll.config

    要么

  • 使用 DeepSpace101 提供的构建后命令

我不想导入更多的依赖项,所以选择了以下内容:

class Main
{
    private static readonly NameValueCollection AppSettings = ConfigurationManager.AppSettings;

    public static void Main(string[] args)
    {
        var appSettings = new MemoryConfigurationSource
        {
            InitialData = AppSettings.AllKeys.ToDictionary(key => key, key => AppSettings[key]),
        };
        var config = new ConfigurationBuilder()
            .AddCommandLine(args)
            .Add(appSettings)
            .Build();
    }
}

只需将 ConfigurationManager.AppSettings 映射到 MemoryConfigurationSource。

我有问题。 我需要在 .Net Core(C#) 中编写一个使用 app.config 的程序,如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="custom" type="ConfigurationSample.CustomConfigurationSection, ConfigurationSample"/>
  </configSections>
  <connectionStrings>
    <add name="sampleDatabase" connectionString="Data Source=localhost\SQLExpress;Initial Catalog=SampleDatabase;Integrated Security=True"/>
  </connectionStrings>
  <appSettings>
    <add key="sampleApplication" value="Configuration Sample"/>
  </appSettings>
  <custom>
    <customConfigurations>
      <add key="customSample" name="Mickey Mouse" age="83"/>
    </customConfigurations>
  </custom>
</configuration>

我写道:

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 - Install-Package CoreCompat.System.Configuration -Version 4.2.3-r4 -Pre 下载,但仍然无法正常工作。 也许有人可以帮助我?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM