Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use custom library/project in T4 text template?

Tags:

c#

reference

t4

I look and I don't see.

I have a solution with two projects -- project A (a library) and project B, which is main project and contains T4 text template.

What I did so far -- I added a reference in main project to project A. I included such line in template:

<#@ import namespace="MyProjectA" #>

Yet, there is still an error "Compiling transformation: The type or namespace name 'MyProjectA' could not be found (are you missing a using directive or an assembly reference?)"

Question: how can I reference to project A from text template?

Please note: I would like to reference a project within the solution, not the dll file on disk.

like image 949
greenoldman Avatar asked Jun 01 '11 09:06

greenoldman


2 Answers

Using $(SolutionDir) references the project via the dll in the bin folder (only way with t4 due to how it resolves assembly names)

<#@ assembly name="$(SolutionDir)MyProject\bin\Applications.Models.dll" #>

(the above solution by Mel using Path.GetDirectoryName didn't work so thought I'd share my experience)

like image 157
atreeon Avatar answered Sep 20 '22 14:09

atreeon


You need to reference the DLL as well using the "assembly" directive. For instance:

<#@ assembly name=“System.Xml” #>

You can reference dlls by their path, as well. See Oleg Sych's T4 series for pretty much anything you would ever want to know. Here is the page about the "assembly" directive: http://www.olegsych.com/2008/02/t4-assembly-directive/

I'm afraid that the T4 template is totally unaware of the solution it lives in, however, so referencing another project in the solution will still have to be done as a dll reference. If you set the HostSpecific attribute in the "template" directive like this:

<#@ template language="C#" debug="false" hostspecific="true" #>

Then you should at least be able to make the path to the other dll relative, although I haven't tried that particular trick myself. You can get the path to the current T4 file by using the Host.TemplateFile property. Try using this to construct the dll reference, such as:

<#@ assembly name=Path.GetDirectoryName(Host.TemplateFile) + “..\OtherProject\bin\Debug\ClassLibrary1.dll” #>

I can't promise that this will work, but it's worth a shot.

like image 32
Mel Avatar answered Sep 19 '22 14:09

Mel