【问题标题】:Transform T4 Template during Build: Method not found 'System.ReadOnlySpan'在构建期间转换 T4 模板:找不到方法 \'System.ReadOnlySpan\'
【发布时间】:2022-08-16 02:48:47
【问题描述】:

我有一个 T4 模板,我想在构建项目时对其进行转换。当我将以下行添加到我的 .csproj 时,Visual Studio 尝试在构建时转换我的模板,但出现异常。

<Import Project=\"$(MSBuildExtensionsPath)\\Microsoft\\VisualStudio\\v17.0\\TextTemplating\\Microsoft.TextTemplating.targets\" />
<PropertyGroup>
    <TransformOnBuild>true</TransformOnBuild>
</PropertyGroup>

例外:

Error       An exception was thrown while trying to compile the transformation code. The following Exception was thrown:
System.MissingMethodException: Method not found: \'System.ReadOnlySpan`1<!0> System.Collections.Immutable.ImmutableArray`1.AsSpan()\'.
   at Microsoft.CodeAnalysis.CryptoBlobParser.IsValidPublicKey(ImmutableArray`1 blob)
   at Microsoft.CodeAnalysis.MetadataReaderExtensions.CreateAssemblyIdentityOrThrow(MetadataReader reader, Version version, AssemblyFlags flags, BlobHandle publicKey, StringHandle name, StringHandle culture, Boolean isReference)
   ...

如果我使用 Visual Studio 在其上“运行自定义工具”,则该模板会成功执行。但是我确实注意到,如果我在模板中删除以下对 System.Memory 程序集的引用,我会在“运行自定义工具”时收到类似的错误

<#@ assembly name=\"System.Memory\" #>

删除该行的错误:

Error       Compiling transformation: The type \'ReadOnlySpan<>\' is defined in an assembly that is not referenced. You must add a reference to assembly \'System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51\'.  Delinea.Permission.Abstractions C:\\Development\\Thycotic\\Delinea.Permission\\src\\SDK\\Delinea.Permission.Abstractions\\Types\\PermissionList.tt  22  

如何让我的 T4 模板在构建期间进行转换?似乎它在构建过程中未能使用 System.Memory 程序集,尽管引用它可以很好地与“运行自定义工具”一起使用。


注意:Invoke text transformation in the build process 的说明建议在我的项目中找到这一行:

<Import Project=\"$(MSBuildToolsPath)\\Microsoft.CSharp.targets\" />

我的任何项目中都没有这条线。添加它会将我的目标框架更改为 .NET Framework 4,这会破坏很多其他的东西。希望这不是必要的部分,因为添加该行会导致更多问题。

    标签: c# build t4


    【解决方案1】:

    添加带有System.Immutable.Collections 的汇编指令。这可能会解决您的问题,但也可能会引入一些额外的问题。请注意,在模板代码中仅使用 netstandard2.0 API 会更安全。混淆来自这样一个事实,即通过 Visual Studio 中的自定义工具运行模板转换并通过 MSBuild 在构建中运行它使用具有不同先决条件的不同主机。

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 2011-11-01
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      相关资源
      最近更新 更多