T4 汇编指令找不到指定的文件

T4 Assembly directive cannot find the file specified

无论使用什么方法在汇编指令中指定文件,T4 引擎都找不到指定的文件。

<#@ assembly name="$(SolutionDir)packages\TestPackage\lib\net45\Test.dll"#>

或 <#@程序集名称="C:\Test.dll"#>

或任何其他方法导致相同的未找到问题。模板引擎似乎能够读取文件并显示其版本信息,即使找不到它。

Errors were generated when initializing the transformation object. The transformation will not be run. The following Exception was thrown:
System.IO.FileNotFoundException: Could not load file or assembly ‘Test, Version=1.0.1.0, Culture=neutral, PublicKeyToken=null’ or one of its dependencies. The system cannot find the file specified.

表示缺少依赖项。程序集没有依赖项。

为什么T4引擎找不到我的程序集?

打包程序集时,存在对 EnvDTE 或其他 COM 互操作类型的外部引用。当在 T4 模板中访问 EnvDTE(或其他 COM)互操作时,它会尝试解析 EnvDTE 的引用,并将解析为试图加载的程序集。这就是文件未找到异常的来源,循环引用。这是由在程序集中嵌入互操作类型引用引起的(出于性能原因默认启用)。

Dave Sexton found this issue 5 years ago:

More specifically, it's typeof(DTE) that is causing Visual Studio to try to load my assembly. My assembly is a .NET 4.0 assembly, and by default the reference to the automation assembly, envdte, was added with the NoPIA feature enabled. This causes the compiler to embed the interop types of envdte into my assembly. Therefore, typeof(DTE) is resolving to the DTE type in my assembly, which causes Visual Studio to require my assembly to be loaded to resolve the DTE type!

为了解决该问题,您必须为引用的 COM 程序集禁用互操作类型的嵌入。

  1. Open the References folder for my project (Visual Studio 2010, .NET 4.0).
  2. For each reference to an automation assembly; e.g., envdte, envdte80, vslangproj, vslangproj2, vslangproj80, etc...
  3. Select the reference and open the Properties window.
  4. Change the Embed Interop Types value to False.

重建原始程序集并尝试加载它。