Skip to content
Nate Radebaugh
Nate Radebaugh
Home
GitHub
Twitter
LinkedIn
Resume

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:

    BackEnd.csproj
    1<ItemGroup>
    2 <Content Include="Models\Model.tt">
    3 <Generator>TextTemplatingFileGenerator</Generator>
    4 <LastGenOutput>Model.ts</LastGenOutput>
    5 </Content>
    6</ItemGroup>
    • 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:
    BackEnd.csproj
    1<PropertyGroup>
    2 <PostBuildEvent>"$(SolutionDir)packages\Mono.TextTransform.1.0.0\tools\TextTransform.exe" "$(ProjectDir)Models\Model.tt" -a=outDir!"$(TargetDir)$(ConfigurationName)\"</PostBuildEvent>
    3</PropertyGroup>

Success!

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...