【问题标题】:Automatically load config by hostname in c#在 C# 中按主机名自动加载配置
【发布时间】:2013-07-29 11:11:20
【问题描述】:

我们在不同的机器上开发一个项目。每台机器都有自己的数据库连接。

目前我们使用外部文件从app.config 中加载数据库配置

<connectionStrings configSource="DB.config" />

现在我希望能够保存不同的文件,例如 DB.BobsPC.configDB.JacksPC.config,其中 BobsPCJacksPC 是调试代码的机器的主机名。应该自动使用正确主机的此配置。

类似:

<connectionStrings configSource="DB.[hostname].config" />

有没有聪明的方法来做到这一点?

【问题讨论】:

  • 您可以尝试在configSource 中包含一个环境变量,以防它自动扩展它们:&lt;connectionStrings configSource="DB.%COMPUTERNAME%.config" /&gt;

标签: c# app-config config


【解决方案1】:

您可以将其添加到每台机器上的 machine.config 中,而不是 .config。

【讨论】:

  • 我对每台机器都有不同的 .configs。我在问关于自动收集“正确”配置
【解决方案2】:
public static string GetConnString()
{
   string connString = ConfigurationSettings.AppSettings[GetConfigKey("database")];
   return connString;
}

public static string GetConfigKey(string baseKey)
{
   string str = baseKey;
   if (GetHostName().StartsWith("BobsPC"))
   {
       // set str = the appropriate string = DB.[hostname].config
   }
   else if (GetHostName().StartsWith("JacksPC"))
   {
       // set str = the appropriate string = DB.[hostname].config
   }
   return str;

}

保留一个配置文件并在运行时使用逻辑来检测要使用的配置子集

【讨论】:

  • 虽然这个答案需要一些更灵活的代码,但我认为这种方法更好,因此您不必为您拥有的每台机器重新编译或重新运行 msbuild。
【解决方案3】:

您可以使用 "XML-Document-Transform Syntax" 通常,此语法适用于 Web 项目,但您可以对其进行调整以用于所有类型的项目。

您必须通过添加/更新 TransformXml-Task 来修改您的项目文件(例如 .csproj)。在下面的示例中,在编译期间通过在 App.config 上应用转换来执行转换。如您所见,任务引用了 $(Configuration) 变量,因此存储了转换命令,例如在 App.DEBUG.config 或 App.RELEASE.config 中。您可以将其更改为您喜欢的任何 msbuild 变量。如果我没记错的话是 $(COMPUTERNAME) 所以你必须把你的转换放到 App.MyMachineName.config 中。

<UsingTask TaskName="TransformXml" 
           AssemblyFile="C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.Tasks.dll"/>
<Target Name="AfterBuild">
  <!-- use App.$(COMPUTERNAME).config for specific machine configuration -->
  <TransformXml Source="App.config" 
                Condition="Exists('App.$(Configuration).config')" 
                Transform="App.$(Configuration).config" 
                Destination="$(OutDir)$(AssemblyName).dll.config"/>
</Target>

完整的说明可通过german blog 获得。

这就是您机器特定配置的样子:

<?xml version="1.0"?>
<!-- "App.MyMachineName.config" - File name corresponds to the transformation task  -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add name="MyDbConnection"
         connectionString="Data Source=MyServer;Initial Catalog=MyDb;" 
         providerName="System.Data.SqlClient"
         xdt:Transform="SetAttributes" 
         xdt:Locator="Match(name)"/>
  </connectionStrings>
</configuration>

或者,您可以使用XSL Syntax

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2021-12-31
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多