Skip to content
Nate Radebaugh
Nate Radebaugh

How to Auto-Run T4 Templates in Visual Studio Builds

April 9, 2020 2:59 PM

T4 templates can be used to auto-generate code, such as creating TypeScript types from C# class/enums. Remove the manual step by automatically running your templates as part of the build process.

In Visual Studio, a T4 text template is a mixture of text blocks and control logic that can generate a text file. The control logic is written as fragments of program code in Visual C# or Visual Basic.

The generated file can be text of any kind, such as a web page, or a resource file, or program source code in any language.

Read more here background here:

Set up your T4 template in your project

  1. Add reference to your T4 templates in your .csproj file:

    2 <Content Include="Models\">
    3 <Generator>TextTemplatingFileGenerator</Generator>
    4 <LastGenOutput>Model.ts</LastGenOutput>
    5 </Content>
    • Note: This is not supported in your .njsproj, so this needs to live in your .csproj
  2. Write your T4 Templates to write the output that you want.

    • Test this by right-clicking the .tt file in Visual Studio and choosing Run Custom Tool

Automate it

This is great, but requiring manual intervention for code generation is so 2019.

  1. Install NuGet package Mono.TextTransform

  2. Run your T4 Text Transforms after the C# code builds:

    • Add the following PostBuildEvent BackEnd.csproj:
    2 <PostBuildEvent>"$(SolutionDir)packages\Mono.TextTransform.1.0.0\tools\TextTransform.exe" "$(ProjectDir)Models\" -a=outDir!"$(TargetDir)$(ConfigurationName)\"</PostBuildEvent>


Now when you build, your generated output will be re-generated after the build succeeds. Whew! 😅

What about pre-build events?

If you need to run your T4 template before the build, such as for T4 MVC, you'll want to use a <PreBuildEvent> instead of the <PostBuildEvent> above in your .csproj file.

Further reading...