Skip to content

How to Auto-Run T4 Templates in Visual Studio Builds

April 9, 2020


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

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

    BackEnd.csproj
    <ItemGroup>
         <Content Include="Models\Model.tt">
             <Generator>TextTemplatingFileGenerator</Generator>
             <LastGenOutput>Model.ts</LastGenOutput>
         </Content>
    </ItemGroup>
    
    • Note: This is not supported in your .njsproj, so this needs to live in your .csproj
  • 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.

  • Install NuGet package Mono.TextTransform

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

    • Add the following PostBuildEvent BackEnd.csproj:
    BackEnd.csproj
    <PropertyGroup>
        <PostBuildEvent>"$(SolutionDir)packages\Mono.TextTransform.1.0.0\tools\TextTransform.exe" "$(ProjectDir)Models\Model.tt" -a=outDir!"$(TargetDir)$(ConfigurationName)\"</PostBuildEvent>
    </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...