T4 transform on build VS2012

So what’s the problem?

Visual Studio has .tt files – so called T4 templates and they are great – generate your code on the fly. Right? Well… sorta. .tt files do that on Ctrl+ S /Save and that’s it. Not exactly on the fly….

And Microsoft does have Modeling SDK for vs2013 or vs2012 that allow for transform on build. But there are potential risks involved like: If you use an .dll that you generate with a previous build project and want it to be dynamic as in when you change the first project the .tt file that uses it to regenerate the result based on the new .dll. But if you include an dll inside of .tt, say like this msbuild loads it in memory and locks it and it can not get changed on the fly like you need it to.

ProjectFoo -> copy result to ..\path\to\foo\bar\Foo.dll
template.tt -> assembly name=”..\path\to\foo\bar\Foo.dll -> generate code as you expect it to

build 1 – Foo.dll gets locked inside of msbuild.exe process

change ProjectFoo
build 2 – try copy result to ..\path\to\foo\bar\Foo.dll but to no avail – it is locked inside of the msbuild process

Or maybe you want to control more closely what and how to generate your files.


Building on top of a great blog I came up with This .targets file for use with visual studio proj files.

How to use it?

  1. Add .tt file and add in it all the assemblies that you need. Using VS standart tt transforming make it the way that you need it
  2. After thar remove the assembly references and remove the custom tool (file properties inside vs) for VS to not try and fail every time you save the tt in generating it
  3. Unload/Edit the project and add reference to the targets file and a list of all dlls needed for your tt inside of proj file like in this csproj file See the end of file.
  4. Build your project and voila – you have code generated on build


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s