Add References To Visual Studio Project From T4 Template
Date: Friday, February 22, 2013 4:00 PM
Posted by: Nico Ploner
Category: T4
This post demonstrates how to add assembly references to the Visual Studio Project the T4 template resides in.
Background
Sometimes the output code generated by a T4 template uses imports from an assembly that has not been referenced by the containing Visual Studio project yet. So on the first build attempt the user receives corresponding compile errors and has to add the references manually.
So why not enable the template to add necessary references to the project while generating the output code?
HowTo
In order to gain access to the Visual Studio project we use classes from the Visual Studio automation classes. This requires the T4 template to reference the EnvDTE.dll and the VsLangProj.dll. Add the following directives to the header of your template:
<#@ assembly name="EnvDTE" #>
<#@ assembly name="VSLangProj" #>
Then we need a reference to the current instance of Visual Studio:
<#
var studio = (this.Host as IServiceProvider).GetService(typeof(EnvDTE.DTE))
as EnvDTE.DTE;
#>
From here we can get the current project object by finding the ProjectItem of the template and accessing its containing project:
<#
var templateItem = studio.Solution.FindProjectItem(this.Host.TemplateFile);
var project = templateItem.ContainingProject;
#>
Unfortunately this project object does not allow to access the assembly references of the project. We need to get a VSProject version of the project:
<#
var vsProject = project.Object as VSLangProj.VSProject;
#>
This object finally allows us to access a collection containing all assembly references of that project.
We can add new references via the full path of a .dll, the name of another project in the solution or assembly names.
<#
vsProject.References.Add(@“C:\SomePath\MyLibrary.dll”);
vsProject.References.Add(“System.Data.Entity”);
vsProject.References.Add(“System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A”);
#>
If a reference to that assembly already exists, there will no exception but the statement is ignored.
Now transform the template and see that all desired references have been added to the current project.
Remarks
A reusable .ttinclude-File that encapsulates the logic of how to add references to a Visual Studio Project is available in the tangible T4 Editor Template Gallery.