How to: Reference Assemblies in Text Templates

The assembly directive lets you specify assemblies that you want to use in a text template. For more information, see Directive Syntax (Domain-Specific Languages).

To reference an assembly from a text template

  1. Add the following directive to the template.

    <#@ assembly name = "C:\Assemblies\Assembly.dll" #>
    

    Note

      You can either specify a strong name for an assembly in the global assembly cache or you can specify a fully qualified path to the file name of the assembly. You can also specify the name of a DLL in the References list of the project that contains the text template.

    The following is an example of how to specify a strong name.

    <@# assembly file="Assembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=0123456789abcdef" #>
    
  2. To access the assembly, add code that resembles the following code.

    <#=Class1.DoSomething();#>
    
    <#=Class1.DoSomething()#>
    

    Note

    In this example, Class1 is a type that is defined in the assembly Assembly.dll.

Developing assemblies that you reference from a text template

  • You cannot rebuild an assembly that is referenced from a text template, for some time after it has been executed in Visual Studio. This is because the Visual Studio text template host keeps the referenced assemblies loaded, and therefore locked, after the template has been executed. This strategy improves performance when there are multiple templates.

    However, it presents a difficulty if you are actively developing and frequently rebuilding an assembly that you reference from a text template. There are several workarounds:

    • Stop and restart the Visual Studio instance in which you ran the text template.

    • Execute the text template using TextTransform.exe, during development of the assembly. For more information, see TextTransform.

    • Execute the assembly in unit tests, without using a text template.

    • Reference a copy of the assembly instead of its build location. This might be a useful tactic in a server build.

    The Visual Studio text template host caches the assemblies that are built from a text template, to reduce the need to recompile templates. You can switch off this behavior by adding the string CacheAssemblies="false" to the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\TextTemplating. On a 64-bit system, use HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\TextTemplating. However, this does not switch off retention of the AppDomain and referenced assemblies.

See Also

Tasks

Walkthrough: Using an Assembly in a Text Template

Other Resources

Using Built-in Directives in Text Templates

Adding Code to Text Templates

Generating Artifacts By Using Text Templates

Change History

Date

History

Reason

Added note about locked assemblies.

Customer feedback.

July 2008

Rewrote and refactored project.

Content bug fix.