i made a T4 template in visual studio recently and started encountering a problem i cant find the reason for.
whenever i edit the template and run it then it performs as expected. if i run it again without editing the template the content is output duplicate. if i run it again, without editing, it adds another duplication, resulting in seeing the output 3 times. and so on.
<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".txt" #>
<#@ Assembly Name="System.Core" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
<#
input.Add("data1");
input.Add("data2");
foreach(var data in input)
{
#>
<#=data#>
<#
}
#>
<#+
static List<string> input = new List<string>();
#>
after some logical thinking i concluded that the template was somehow ‘remebering’ my inputs. and then i thought that it might be the static class feature i inluded for collecting my inputs. removing it fixed the problem! how it came about that there was a static in the first place was because i first tested most of the complex initialization logic in a console application and just copied it to the template.
conclusion:
so it seems that visual studio builds a library from your T4 template when you save it and also loads it into an appdomain and then executes it. and it will reuse this loaded library until you edit yout template. and thats how this static variable remebered the inputs from the previous time the template was run – its still alive.
as a side note, next time i will test my initialization code inside a class instance instead of next to static void main()!