T4文本模板无法调用其他代码



打开VisualStudio2022并创建一个新的net6.0类库。

创建一个要在T4模板中使用的类,然后创建一个T4模板并使用该类。

类别:

namespace ClassLibraryT4
{
public class Class1
{
public static string DoTheThing() { return "TheThing"; }
}
}

现在构建项目,使其dll文件存在于光盘上。

T4:

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="$(SolutionDir)ClassLibraryT4binDebugnet6.0ClassLibraryT4.dll" #>
<#@ import namespace="ClassLibraryT4" #>
<#@ output extension=".cs" #>
namespace ClassLibraryT4 
{
public class TheGeneratedClass
{
private const string _TheThing = "<# Class1.DoTheThing(); #>";
}
}

T4现在无法运行,因为

类型"Object"是在未引用的程序集中定义的。必须添加对程序集"System"的引用。运行时,版本=6.0.0.0,区域性=中性,PublicKeyToken=b03f5f7f11d50a3a'。

如果我添加到T4:

<#@ assembly name="System.Runtime"#>

然后我现在得到

Error       Running transformation: System.IO.FileNotFoundException: Could not load file or assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
at Microsoft.VisualStudio.TextTemplating6765B00A4659E4D1054752E9A2C829A21EECD20197C4EDDD8F5675E0DB91730A0DFF4528F1622E70821097EC90F6A2D0DE05F4739B3E0CD1BCAF45AAA20D419D.GeneratedTextTransformation.TransformText()
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at Microsoft.VisualStudio.TextTemplating.TransformationRunner.PerformTransformation()

T4能工作吗?

似乎不可能使用任何outisde代码;该在T4:中起作用

private const string _TheThing = "<#= 5+2 #>";

这个也是:

private const string _TheThing = "<#= Thing() #>";
...
<#+ 
private static string Thing() {
return "thing";
}
#>

但这也具有_无法加载文件或程序集系统。运行时…`问题:

<#+ 
private static string Thing() {
return Class1o.DoTheThing();
}
#>

T4能工作吗?对您只需要确保所有使用的dll都适用于x86体系结构。这是Visual Studio的限制,因为它是一个32位的应用程序。

实现此功能最安全的方法是对要加载到T4模板中的任何程序集使用netstandard2.0。如果您只包含普通的C#代码(通过include指令(,那么即使它在调整了汇编指令一段时间后使用了net6.0API,您也可以不受影响。但是,您需要对其进行调整,使其同时适用于Visual StudioMSBuild主机。

最新更新