Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T4 Templates: Import namespace in host assembly

Tags:

c#

t4

All,

I have a T4 Template

<#@ template debug="true" hostSpecific="true" #>
<#@ output extension=".cs" #>
<#@ Assembly Name="System.Core" #>
<#@ Assembly Name="System.Windows.Forms" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Diagnostics" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="MyLibrarysRootNameSpace.SomeNamespace" #>
/*Rest of template follows*/

I'm trying to get the last line to import so that I can easily resuse this template in other projects, but I seem to be missing something. Is what I am trying to do possible? If so, how?

like image 742
William Avatar asked Apr 12 '13 23:04

William


2 Answers

Import just adds a using statement, it does not reference the assembly. T4's referenced assembly set is completely divorced from the project that is hosting the template.

If you want to bring in your hosting project's assembly then you need an assembly directive to do it. Something like the following:

<#@ assembly name="$(TargetPath)" #>

Note that you are introducing a build loop here, so the project will need manual intervention to build until it has produced a DLL once, so make sure you only generate partials that are optional or can always use the previous checked in version.

like image 52
GarethJ Avatar answered Nov 15 '22 07:11

GarethJ


If I understood your question correctly:

Copy-paste the first 2 snippets from there to get the EnvDTE object model for the project that contains the T4:

<#@ assembly name="EnvDte" #>
<#
    var visualStudio = ( this.Host as IServiceProvider )
        .GetService( typeof( EnvDTE.DTE ) ) as EnvDTE.DTE;
    var project = visualStudio.Solution
        .FindProjectItem( this.Host.TemplateFile )
        .ContainingProject as EnvDTE.Project;
#>

Then, use the method from there to obtain the default namespace of that project:

// project is of type: EnvDTE.Project
string strDefaultNamespace = project.Properties.Item( "DefaultNamespace" )
    .Value.ToString();

Then, use strDefaultNamespace value however your like.

like image 22
Soonts Avatar answered Nov 15 '22 06:11

Soonts