4

我正在尝试使用 T4 模板在我的项目中自动生成一些代码使用。我从小开始弄湿我的“脚”,这就是我到目前为止所拥有的。

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="C:\Users\username\Documents\Visual Studio 2012\Projects\MyProjectSolution\MyProject\bin\Debug\MyProject.exe" #>
namespace KY_ADJRATE_CLAIM
{
    public class OutboundClaim
    {
<#
    ClaimConfig cc;
 #>
    }
}

我试过这个

<#@ assembly name="C:\Users\username\Documents\Visual Studio 2012\Projects\MyProjectSolution\MyProject\bin\Debug\MyProject.exe" #>

和这个

<#@ assembly name="MyProject.exe" #>

但是每次我尝试创建我的一个类的实例时,我都会得到这个:

命名空间不能直接包含字段或方法等成员。编译转换:找不到类型或命名空间名称“ClaimConfig”(您是否缺少 using 指令或程序集引用?)

我想要做的是通过 T4 模板访问我项目中的 ClaimConfig 类。

任何帮助将不胜感激。

4

2 回答 2

7

这类似于我过去看到的另一个问题(如何在 T4 文本模板中使用自定义库/项目?)。您需要使用“程序集”指令来引用 DLL。例如:

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

为了从您自己的项目或解决方案中引用 DLL,您可以使用相对路径,但首先您必须在“模板”指令中设置 HostSpecific 属性,如下所示:

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

然后,您可以使用 $(SolutionDir) 宏来获取解决方案的根,并从那里构造到 DLL 的相对路径,如下所示:

<#@ assembly name="$(SolutionDir)\MyOtherProject\bin\Debug\MyOtherAssembly.dll” #>
于 2013-12-04T20:50:10.617 回答
5

I strongly suggest that you separate all common classes (this is, classes that will be used in T4 and outside T4) in a common assembly, which can then be referenced by your project and your T4 Templates:

 MySolution
 |
 | -> MyProject.Common
 |    |--> ClaimConfig.cs
 | 
 | -> MyProject.Main
 |    |--> References
 |    |    |--> MyProject.Common
 |    | MyT4Template.tt

So that the compilation of MyProject.Common (which contains all classes needed to successfully compile the Main project AND the T4 Templates) is separated.

Then in your template:

<#@ assembly name="C:\Users\username\Documents\Visual Studio 2012\Projects\MyProjectSolution\MyProject.Common\bin\Debug\MyProject.Common.dll" #>

Also, I strongly suggest you use a T4 Editor, such as Tangible T4 Editor, it's going to help you A LOT when editing T4 templates, mainly because it clearly highlights and makes a visual difference between "resulting code" (I.E the template output) and "generating code" (the code inside the template). They provide a free version, as well as a commercial full version. I use the free version and it has been really helpful so far.

于 2013-10-14T16:26:56.517 回答