简体   繁体   English

在 .Net Core 中使用 app.config

[英]Using app.config in .Net Core

I have problem.我有问题。 I need to write a program in.Net Core(C#) which use app.config like this:我需要在 .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>

and I write:我写:

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

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

and it is example from the inte.net so I thought would work, but I am getting exceptions:它是来自 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).

I downloaded via NuGet - Install-Package CoreCompat.System.Configuration -Version 4.2.3-r4 -Pre and still don't work.我通过 NuGet - Install-Package CoreCompat.System.Configuration -Version 4.2.3-r4 -Pre 下载但仍然无法正常工作。 Maybe someone can help me?也许有人可以帮助我?

It is possible to use your usual System.Configuration even in .NET Core 2.0 on Linux.即使在 Linux 上的 .NET Core 2.0 中,也可以使用您常用的System.Configuration Try this test example:试试这个测试示例:

  1. Created a .NET Standard 2.0 Library (say MyLib.dll )创建了一个 .NET Standard 2.0 库(比如MyLib.dll
  2. Added the NuGet package System.Configuration.ConfigurationManager v4.4.0.添加了 NuGet 包System.Configuration.ConfigurationManager v4.4.0。 This is needed since this package isn't covered by the meta-package NetStandard.Library v2.0.0 (I hope that changes)这是必需的,因为元包NetStandard.Library未涵盖此包(我希望有所改变)
  3. All your C# classes derived from ConfigurationSection or ConfigurationElement go into MyLib.dll .ConfigurationSectionConfigurationElement派生的所有 C# 类都进入MyLib.dll For example MyClass.cs derives from ConfigurationSection and MyAccount.cs derives from ConfigurationElement .例如, MyClass.cs派生自ConfigurationSection ,而MyAccount.cs派生自ConfigurationElement Implementation details are out of scope here but Google is your friend .实施细节超出了此处的范围,但Google 是您的朋友
  4. Create a .NET Core 2.0 app (eg a console app, MyApp.dll ).创建 .NET Core 2.0 应用程序(例如控制台应用程序MyApp.dll )。 .NET Core apps end with .dll rather than .exe in Framework. .NET Core 应用程序以.dll而不是 Framework 中的.exe结尾。
  5. Create an app.config in MyApp with your custom configuration sections.使用您的自定义配置部分在MyApp中创建一个app.config This should obviously match your class designs in #3 above.这显然应该与上面#3 中的类设计相匹配。 For example:例如:

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

That's it - you'll find that the app.config is parsed properly within MyApp and your existing code within MyLib works just fine.就是这样 - 您会发现 app.config 在MyApp中被正确解析,并且您在MyLib中的现有代码工作得很好。 Don't forget to run dotnet restore if you switch platforms from Windows (dev) to Linux (test).如果将平台从 Windows (dev) 切换到 Linux (test),请不要忘记运行dotnet restore

Also, the location of app.config at runtime is different than what was in .net framework, instead of "projectName.exe.config".此外,app.config 在运行时的位置不同于 .net 框架中的位置,而不是“projectName.exe.config”。 It is now "projectName.dll.config" in .net core.它现在是 .net 核心中的“projectName.dll.config”。

Additional workaround for test projects测试项目的其他解决方法

If you're finding that your App.config is not working in your test projects, you might need this snippet in your test project's .csproj (eg just before the ending </Project> ).如果您发现您的App.config在您的测试项目中不起作用,您可能需要在您的测试项目的.csproj中使用此代码段(例如,就在结尾</Project>之前)。 It basically copies App.config into your output folder as testhost.dll.config so dotnet test picks it up.它基本上将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. You can use Microsoft.Extensions.Configuration API with any .NET Core app, not only with ASP.NET Core app.您可以将Microsoft.Extensions.Configuration API任何.NET Core 应用程序一起使用,而不仅仅是与 ASP.NET Core 应用程序一起使用。 Look into sample provided in the link, that shows how to read configs in the console app.查看链接中提供的示例,它显示了如何在控制台应用程序中读取配置。

  2. In most cases, the JSON source (read as .json file) is the most suitable config source.在大多数情况下,JSON 源(读取为.json文件)是最合适的配置源。

    Note: don't be confused when someone says that config file should be appsettings.json .注意:当有人说配置文件应该是appsettings.json时,请不要感到困惑。 You can use any file name, that is suitable for you and file location may be different - there are no specific rules.您可以使用任何适合您的文件名,文件位置可能不同——没有特定规则。

    But, as the real world is complicated, there are a lot of different configuration providers:但是,由于现实世界很复杂,所以有很多不同的配置提供程序:

    • File formats (INI, JSON, and XML)文件格式(INI、JSON 和 XML)
    • Command-line arguments命令行参数
    • Environment variables环境变量

    and so on.等等。 You even could use/write a custom provider.您甚至可以使用/编写自定义提供程序。

  3. Actually, app.config configuration file was an XML file.实际上, app.config配置文件是一个 XML 文件。 So you can read settings from it using XML configuration provider ( source on github , nuget link ).因此,您可以使用 XML 配置提供程序( github 上的源代码nuget 链接)从中读取设置。 But keep in mind, it will be used only as a configuration source - any logic how your app behaves should be implemented by you.但请记住,它将仅用作配置源 - 您的应用程序行为方式的任何逻辑都应由您实现。 Configuration Provider will not change 'settings' and set policies for your apps, but only read data from the file. Configuration Provider 不会更改“设置”并为您的应用设置策略,而只会从文件中读取数据。

I have a.Net Core 3.1 MSTest project with similar issue.我有一个具有类似问题的 .Net Core 3.1 MSTest 项目。 This post provided clues to fix it.这篇文章提供了修复它的线索。

Breaking this down to a simple answer for.Net core 3.1:将其分解为 .Net core 3.1 的简单答案:

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

If it is a MSTest project:如果是 MSTest 项目:

  • rename file in project to testhost.dll.config将项目中的文件重命名为 testhost.dll.config

    OR要么

  • Use post-build command provided by DeepSpace101使用 DeepSpace101 提供的构建后命令

I didn't want to import further dependencies, so settled on the following:我不想导入更多的依赖项,所以选择了以下内容:

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();
    }
}

Just mapping ConfigurationManager.AppSettings to MemoryConfigurationSource.只需将 ConfigurationManager.AppSettings 映射到 MemoryConfigurationSource。

I have problem.我有问题。 I need to write a program in .Net Core(C#) which use app.config like this:我需要在 .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>

and I write:我写道:

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

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

and it is example from the internet so I thought would work, but I am getting exceptions:这是来自互联网的例子,所以我认为会起作用,但我得到了例外:

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).

I downloaded via NuGet - Install-Package CoreCompat.System.Configuration -Version 4.2.3-r4 -Pre and still don't work.我通过 NuGet - Install-Package CoreCompat.System.Configuration -Version 4.2.3-r4 -Pre 下载,但仍然无法正常工作。 Maybe someone can help me?也许有人可以帮助我?

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

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