2013-07-29 2 views
2

다른 컴퓨터에서 프로젝트를 개발합니다. 이러한 각 시스템에는 자체 데이터베이스 연결이 있습니다. BobsPCJacksPC는 시스템의 호스트 이름입니다 호스트 이름별로 구성을 자동으로로드 C#

현재 우리는

<connectionStrings configSource="DB.config" /> 

가 지금은 DB.BobsPC.configDB.JacksPC.config처럼 다른 파일을 저장할 수 있도록하려면 외부 파일을 사용하여 app.config 내에서 데이터베이스 설정을로드 코드가 디버깅됩니다. 이 올바른 호스트 구성은 자동으로 사용되어야합니다. 같은

뭔가 :

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

이 할 수있는 현명한 방법이 있나요?

+0

당신 수 오프 기회에,'configSource'에서 환경 변수를 포함하십시오 '' – Cocowalla

답변

4

당신은 일반적으로 "XML-Document-Transform Syntax"을 사용할 수 있습니다 사용하는 구성의 어느 부분 집합 감지하는 런타임에 논리를 사용,이 구문 IST는 웹에서 사용하기위한 것 모든 종류의 프로젝트에서 사용할 수 있도록 조정할 수 있습니다.

TransformXml-Task를 추가/업데이트하여 프로젝트 파일 (예 : .csproj)을 수정해야합니다. 아래 예에서 변환은 Appilation에서 변환을 적용하여 편집 중에 실행됩니다. 보시다시피, 작업은 $ (구성) 변수를 참조하므로 변환 명령이 저장됩니다. 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입니다.

는 기계 특정 구성의 모습 that`s : 또는

<?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

1

.config 대신 개별 컴퓨터의 machine.config에 추가 할 수 있습니다.

+0

각 컴퓨터마다 다른 .configs가 있습니다. 자동으로 "올바른"구성을 수집하는 것에 대해 묻고있었습니다. –

3
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; 

}

는 하나의 설정 파일을 유지하고

+0

이 대답에 좀 더 유연한 코드가 필요하지만이 방법이 더 좋다고 생각합니다. 따라서 각 컴퓨터에 대해 msbuild를 다시 컴파일하거나 다시 실행할 필요가 없습니다. – user2415376

관련 문제