Code Generation with T4
WHAT’S IN THIS CHAPTER?
- Using T4 templates to generate text and code
- Troubleshooting T4 templates
- Creating Runtime T4 template to include templating in your projects
Frequently, when writing software applications, you’ll have large areas of boilerplate code in which the same pattern is repeated over and over. Working on these areas of code can be time-consuming and tedious, which leads to inattention and easily avoidable errors. Writing this code is a task best suited to automation.
Code generation is a common software engineering practice where some mechanism, rather than a human engineer, is used to write program components automatically. The tool used to generate the code is known as a code generator. A number of commercial and free code generators are available in the market, from the general to those targeted toward a specific task.
Visual Studio 2012 includes a code generator that can generate files from simple template definitions. This code generator is the Text Template Transformation Toolkit, or more commonly, T4.
T4 was originally introduced as part of the Domain Specific Languages Toolkit, which was an add-in for Visual Studio 2005. T4 was included out of the box in Visual Studio 2008, but it was poorly documented, and there were few hints in the IDE that it existed. Visual Studio 2010 made T4 a first-class citizen so that Text Template is now one of the options in the File ⇒ New dialog.
This chapter explores the creation, configuration, ...