How to output namespace in T4 templates?

邮差的信 提交于 2019-11-30 01:27:01

If you're using Visual Studio 2010, you can retrieve the namespace by checking the CallContext's "NamespaceHint" property.

System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint");
Oleg Sych

Here is what you can do with T4 Toolbox:

<#@ template language="C#v3.5" hostspecific="True" debug="True" #> 
<#@ include file="T4Toolbox.tt" #>
<# 
  var namespaceName = TransformationContext.DefaultNamespace; 
#> 

DefaultNamespace property of TransformationContext class returns a string with namespace based on the root namespace of your project and the location of your .tt file in it (i.e. it treats folders as namespaces). This way you don't have to specify Custom Tool Namespace property for every instance of your .tt file.

If you prefer to use the Custom Tool Namespace property, you can pass Host.TemplateFile to the GetCustomToolNamespace method posted by @sixlettervariables.

Damien Guard includes some code in a blog posting which retrieves the Custom Tool Namespace for a given file:

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

How I've done this:

<#@ 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 #> {

}

If you use Visual Studio 2012

EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
string namespaceName = System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint").ToString();

EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);

Aldo Flores @alduar

The accepted answer doesn't work on Visual Basic Projects. I had to use the method from: http://lennybacon.com/post/2010/12/10/generatingcodefileswithcorrectnamespacesusingt4

var hostServiceProvider = (IServiceProvider)Host;
var dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE));
var activeSolutionProjects = (Array)dte.ActiveSolutionProjects;
var dteProject = (EnvDTE.Project)activeSolutionProjects.GetValue(0);
var defaultNamespace = dteProject.Properties.Item("DefaultNamespace").Value;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!