Get referenced project's path in T4 template?

Jaxidian picture Jaxidian · Aug 23, 2010 · Viewed 19.1k times · Source

I have a solution that has a few projects in it. I'd like to create some T4 templates in one of my test projects to generate tests based on code in another project. The test project has a Project Reference to the other project. The problem I have is that I don't know how to get a file path to the edmx file I need to generate code from.

Example (pretend this is an ASCII-based Solution Explorer):

MySolution.sln
-> MyTests.csproj (C:\a\b\c\)
----> GeneratedTests.tt (C:\a\b\c\GeneratedTests.tt)
-> MyDAL.csproj (C:\x\y\z\)
----> MyModel.edmx (C:\x\y\z\MyModel.edmx)

How would my GeneratedTests.tt be able to get a file path for MyModel.edmx utilizing its project reference to it?

Answer

Michael L Perry picture Michael L Perry · Aug 29, 2010

This answer only works from within Visual Studio.

Set the "hostspecific" property of the T4 template. This gives you access to the Host property. Type cast Host to IServiceProvider to call GetService(typeof(DTE)). This lets you traverse the contents of the solution.

<#@ template language="c#" hostspecific="true"  #>
<#@ assembly name="EnvDTE" #>
<#@ import namespace="EnvDTE" #>
These are the projects in this solution:
<#
var serviceProvider = this.Host as IServiceProvider;
var dte = serviceProvider.GetService(typeof(DTE)) as DTE;
foreach (Project p in dte.Solution.Projects)
{
#>
    <#=p.Name#> at <#=p.FullName#>
<#
}
#>

Also see the example of the ITextTemplatingEngineHost interface on MSDN and T4 Architecture by Oleg Synch.