簡體   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