Tuesday 4 October 2011

T4 Import Directive - Namespace Alias

How do you specify a namespace alias when using the Import directive in a T4 template?

The Import directive in a T4 template is used to bring a namespace into scope for any code that will be run when processing the T4 template. Here is an example template that imports the System.IO namespace without using a namespace alias.

<#@ template language="C#" #> 
<#@ output extension=".txt" #> 
<#@ import namespace="System.IO" #> 
<# 
 string text = File.ReadAllText(@"d:\MyFile.txt"); 
#> 
File content: <#= text #>

The T4 template reads all the text in the d:\MyFile.txt which is then saved in the file generated by the template.

If we want to use a namespace alias we can specify it in the import directive in a similar way to how you can with C# or VB.NET. Here is the example template modified so that an alias of IO is used for the System.IO namespace.

<#@ template language="C#" #> 
<#@ output extension=".txt" #> 
<#@ import namespace="IO = System.IO" #> 
<# 
 string text = IO.File.ReadAllText(@"d:\temp\test.xsd"); 
#> 
File content: <#= text #>

Why does this Work?

T4 templates use the CodeDom to generate C# or VB.NET code which is then executed as the template is processed. When the T4 templating engine processes the Import directive it creates a CodeNamespaceImport object and passes it the Namespace attribute's value. The CodeNamespaceImport object supports generating a namespace alias when you specify a string of the form "Alias = Namespace" and pass this to its constructor.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.