Get The ProjectItem of a T4 Template From Inside the T4 Template
So you got a T4 template and need access to the ProjectItem of that T4 template or to the parent Project of the T4 template? Here’s how:
- Set the template’s hostspecific attribute to true and reference the Visual Studio Automation assemblies.
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="envdte" #>
<#@ assembly name="envdte80" #>
<#@ import namespace="EnvDTE" #>
- Get the Project or ProjectItem using Visual Studio Automation.
// By setting the template's 'hostspecific' property to true,
// we get access to the text templating engine host
// which implements IServiceProvider.
var serviceProvider = (IServiceProvider)this.Host;
// Get the automation root object
var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE));
// Get the project item
var projectItem = dte.Solution.FindProjectItem(this.Host.TemplateFile);
// Get the project
var project = projectItem.ContainingProject;
Category: Code Generation