如何在T4模板中输出命名空间?

Hal*_*rim 30 c# t4 code-generation visual-studio

我有一个T4模板,用于在Visual Studio中使用TextTemplatingFileGenerator自定义工具设置的类:

<#@ template language="C#v3.5" hostspecific="True" debug="True" #>
<#
  var className = System.IO.Path.GetFileNameWithoutExtension(Host.TemplateFile);
  var namespaceName = "MyNamespace";
#>

namespace <#= namespaceName #>
{
    public static class <#= className #>
    {
        // some generated code
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在Visual Studio中获取"自定义工具命名空间"属性的值,因此我不必对命名空间进行硬编码?

我甚至会对C#项目的默认命名空间感到满意.

Gar*_*thJ 48

如果您使用的是Visual Studio 2010,则可以通过检查CallContext的"NamespaceHint"属性来检索命名空间.

System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint");
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,这个技巧在使用基于 MSBuild 的转换系统时不起作用(如下所示:http://www.olegsych.com/2010/04/understanding-t4-msbuild-integration/)。无赖。:( (2认同)

Ole*_*ych 13

您可以使用T4 Toolbox执行以下操作:

<#@ template language="C#v3.5" hostspecific="True" debug="True" #> 
<#@ include file="T4Toolbox.tt" #>
<# 
  var namespaceName = TransformationContext.DefaultNamespace; 
#> 
Run Code Online (Sandbox Code Playgroud)

TransformationContext类的DefaultNamespace属性返回一个带有命名空间的字符串,该字符串基于项目的根命名空间和.tt文件的位置(即它将文件夹视为命名空间).这样,您就不必为.tt文件的每个实例指定Custom Tool Namespace属性.

如果您更喜欢使用自定义工具命名空间属性,则可以将Host.TemplateFile传递给@sixlettervariables发布的GetCustomToolNamespace方法.


use*_*116 8

Damien Guard在博客文章中包含一些代码,用于检索给定文件的自定义工具命名空间:

public override String GetCustomToolNamespace(string fileName)
{
    return dte.Solution.FindProjectItem(fileName).Properties.Item("CustomToolNamespace").Value.ToString();
}
Run Code Online (Sandbox Code Playgroud)


Dam*_*iel 5

我是如何做到的:

<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>

<# 
    // Get value of 'Custom Tool Namespace'
    var serviceProvider = (IServiceProvider)this.Host;
    var dte = (DTE)serviceProvider.GetService(typeof(DTE));    
    var Namespace = dte.Solution.FindProjectItem(this.Host.TemplateFile).Properties.Item("CustomToolNamespace").Value;
 #>

namespace <#= Namespace #> {

}
Run Code Online (Sandbox Code Playgroud)