T4 Templates and Code Generation

Wouldn’t it be cool if we could dynamically or problematically create code to help use from having to mundanely do it ourselves?  Well, that awesomeness has been found and it is called T4 Templates.  We have used them a few times in the past to create some simple extensions for Visual Studio but thought it would be a good experience to share with others who are looking for ways to build code dynamically.

T4 stands for Text Template Transformation Toolkit which is kind of lengthy but pretty descriptive when you think about it.  We will be creating a text template that gets transformed into code via this toolkit.  So, where to begin? Well, there are plenty of tutorial out on how to get going so we won’t go into much detail there but maybe some sample code could help describe how developers at Thinkovator are using it.
At the bottom I have pasted a snippet of a template but wanted to give a brief idea of what is going on.
  • At the very top you are able to specify the type of language that will be used throughout the document for any coding specific tasks.
  • If you creating a template that needs to have parameters passed in via the command line or through code using the syntax <#@ parameter name=”someName” type=”typeOfParam” #> will allow parameters to be passed in.
  • Using the syntax <# #> will allow you to add coding logic to them template if a decision has to be made for when parts of the template should be written.
<#@ template language="C#" #>
<#@ parameter name="BaseClassName" type="System.String" #>
<#@ parameter name="CreatedRepo" type="System.Boolean" #>
<#@ parameter name="ProjectName" type="System.String" #>
namespace <#= ProjectName #>
{
	public class <#= BaseClassName #>Service : I<#= BaseClassName #>Service
	{
	<# 
	if (CreatedRepo)
	{
		var lowerBaseClassname = BaseClassName.ToLower();
	#>
		private readonly I<#= BaseClassName #>Repository _<#= lowerBaseClassname #>Repository;

		public <#= BaseClassName #>Service(I<#= BaseClassName #>Repository <#= lowerBaseClassname #>Repository)
		{
			_<#= lowerBaseClassname #>Repository = <#= lowerBaseClassname #>Repository;
		}
	<#
	}
	#>
    }
}

Final note – if you want to have a look at some other templates there are more available on my github account

Leave a Reply

Your email address will not be published. Required fields are marked *