2011-08-08 67 views
4

我們使用t4模板來管理項目中的配置。 web.config文件是通過web.tt文件生成的。在的csproj文件生成後,我有以下:t4在csproj文件中生成沒有DependentUpon屬性的文件

<Content Include="Web.config"> 
    <AutoGen>True</AutoGen> 
    <DesignTime>True</DesignTime> 
    <DependentUpon>Web.tt</DependentUpon> 
</Content> 

是否有可能以某種方式配置T4模板來生成獨立的web.config文件,不屬於web.tt?

Web.config file depends upon web.tt

+0

我能問爲什麼這有差別? –

+0

http://nuget.codeplex.com/workitem/1210 – Sly

+1

不是很乾淨,但您可以從項目中刪除web.tt並使用TextTransform.exe創建web.config文件(http://msdn.microsoft.com/ en-us/library/bb126245.aspx)作爲預先或後期構建操作?最終這似乎是nuget的一個問題,但是當你在等待bug修復時,也許這可以減輕你的痛苦。 – FuleSnabel

回答

3

是的,你可以。首先在T4包含文件中定義一個保存例程。

SaveOutput.tt

<#@ template language=「C#」 hostspecific=「true」 #> 
<#@ import namespace=「System.IO」 #> 
<#+ 
    void SaveOutput(string fileName) 
    { 
     string templateDirectory = Path.GetDirectoryName(Host.TemplateFile); 
     string outputFilePath = Path.Combine(templateDirectory, fileName); 
     File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString()); 

     this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length); 
    } 
#> 

現在每次調用SaveOutput一個文件名時,將寫入當前緩衝區到外部文件。例如。

Web.tt

<#@ include file=「SaveOutput.tt」 #> 
<# 
    GenerateConfig(); 
    SaveOutput(」..\..\Web.Config」); 
#> 

如果要生成多個文件:

<#@ include file=「SaveOutput.tt」 #> 
<# 
    GenerateFile1(); 
    SaveOutput(」..\..\File1.txt」); 

    GenerateFile2(); 
    SaveOutput(」..\..\File2.txt」); 
#>