tangible T4 Directives
The tangible T4 Editor extends the set of existing T4 Directives that can be used inside T4 Text Template files. This list gives an overview on additional directives that can be used when working with the tangible T4 Editor.
The documentation of the basic T4 Text Template Directives is availabl in this MSDN Article.
Directive: newAppDomain
Purpose
Ensures a new AppDomain is created for each template transformation.
Syntax
<#@ newAppDomain processor=”tangibleT4Editor” #>
Background
In some special cases T4 Templates that use external libraries do not work every time they are executed. This is not due to tangible T4 Editor but due to the face that Visual Studio keeps the AppDomain to execute the template between executions. This directive allows you to disable the reuse of AppDomains and assures any static caches in external types from dlls are cleared that way.
Sample
A template references and uses an assembly that provides internal caching. Without the <#@ newAppDomain #> directive the output of the template transformation will be the same. Adding the directive will result in different output every time.
ClassLibrary1.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SomeLibraryWithInternalCaching
{
public class SomeClassWithInternalCaching
{
// Assume this code is somewhere in your template or a DLL your
// template referes to. Then you will need to assure your code
// is always executed in a new AppDomain
static string myCache = null;
string GetSomeValueCached()
{
if (myCache == null)
{
myCache = "Retrieve Value " + new Random().Next();
}
return myCache;
}
}
}
Template.tt
<#@ assembly name="$(ProjectDir)..\ClassLibrary1\bin\Debug\classlibrary1.dll" #>
<#@ newAppDomain processor=”tangibleT4Editor” #>
<#
var MyClass = new SomeLibraryWithInternalCaching.SomeClassWithInternalCaching();
#>
//Issue a Caching Library returns always same value for 15 - 20 template generations
var GetCachedValue = <#= MyClass.GetSomeValueCached() #>;
var AppDomain_ID = <#= AppDomain.CurrentDomain.GetHashCode() #>;