T4: Extending the Generated Template Class by Mike Pagel


Mike Pagel recently posted an interesting article about T4 on CodeProject called “T4: Extending the Generated Template Class“. In this article, Mike describes several approaches for implementing code generation logic - helper methods defined in class feature blocks, custom directive processors and a custom TextTransformation base class referenced using the inherits attribute of the template directive. Mike has chosen the latter approach because it is simpler than writing custom directive processors, offers full IDE support during development of .cs files compared to .tt files, and helps to separate complex logic from the “presentation” code.

This is a viable approach. I have considered it as well but abandoned using it because of the assembly locking problem. When T4 runs the compiled TextTransformation, it loads the Assembly that contains its base class in the templating AppDomain and locks the DLL file. This prevents you from being able to recompile any changes you make in the base class. Unless you restart Visual Studio, the DLL will remain locked for up to 25 template transformations. You could turn off assembly caching, but the DLL will still remain locked unless you run another template that doesn’t reference it. I found locking to be too inconvenient for the TDD style I use when writing T4 templates, which tends to result in numerous quick write-compile-run iterations.

In my own development, I prefer using class feature blocks to define nested classes and pulling them into the main template file with the help of include directives. I agree that current support for developing T4 templates in Visual Studio is very limited. However, T4 Editor makes it a lot better.


Write a Comment

Take a moment to comment and tell us what you think. Some basic HTML is allowed for formatting.

Reader Comments

Be the first to leave a comment!