How to output namespace in T4 templates?

Hallgrim picture Hallgrim · Jan 11, 2010 · Viewed 12.6k times · Source

I have a T4 template for a class set up with TextTemplatingFileGenerator Custom Tool in Visual Studio:

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

How can I get the value of the "Custom Tool Namespace" property in Visual Studio, so I don't have to hardcode the namespace?

I would even be happy with the default namespace for the C# project.

Answer

GarethJ picture GarethJ · Jun 5, 2010

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");