T4 模板无法加载文件或程序集“System.Runtime,版本 = 4.2.0.0”

Dil*_*ena 5 c# t4 visual-studio-2017 asp.net-core-2.0

所以我有一个 T4 模板,我试图在设计时运行,但它一直给我以下错误。

Running transformation: System.IO.FileNotFoundException: Could not load 
file or assembly 'System.Runtime, Version=4.2.0.0, Culture=neutral, 
PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system 
cannot find the file specified.
File name: 'System.Runtime, Version=4.2.0.0, Culture=neutral, 
PublicKeyToken=b03f5f7f11d50a3a'
Run Code Online (Sandbox Code Playgroud)

我的 Visual Studios 解决方案包含 10 个项目,所有项目都针对 .Net Core 2.0 框架。我的 T4 模板目前看起来是这样的:

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="Services.Resources.DataTransferObjects.Infrastructures" #>
<#@ import namespace="System.Collections.Generic" #> 
<#@ assembly name="$(TargetDir)Services.dll" #>


<#@ output extension=".cs" #>
public class AdminDTO
{
        <#var editableObjs = Assembly
            .GetAssembly(typeof(GenericEditable<>))
            .GetTypes()
            .Where(p => p.BaseType != null && p.BaseType.IsGenericType && p.BaseType.GetGenericTypeDefinition() == (typeof(GenericEditable<>)))
            .ToList();
        #>
}
Run Code Online (Sandbox Code Playgroud)

目前我只需要我在模板中引用的程序集,它是一个 .Net Core 2.0 类库项目。我已经尝试在这个特定的库中添加 System.Runtime.dll 引用,但它似乎没有任何区别。

我已经阅读了其他几个与此类似的问题,一般来说 .Net Core 似乎对 T4 模板有问题,但似乎大多数人的解决方案都是针对 .Net Standard 库的。我不确定这是否适用于我,因为我的整个解决方案只涉及 .Net Core 项目。

编辑

我将所有项目更改为面向 .Net Standard 2.0 而不是 .Net Core,这解决了我最初的问题,但现在我看到了这个错误:

System.Reflection.ReflectionTypeLoadException: Unable to load one or 
more of the requested types. Retrieve the LoaderExceptions property for 
more information.
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
Run Code Online (Sandbox Code Playgroud)

lmc*_*iro 11

我找到了System.Runtimedll 错误的解决方法。

把这个 bindingRedirect 放在C:\Users\<user>\AppData\Local\Microsoft\VisualStudio\15.0_29f8d23a\devenv.exe.config里面<configuration>-> <runtime>-><assemblyBinding>所有其他的 bindingRedirect 在哪里

<dependentAssembly>
  <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
  <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="4.0.0.0"/>
</dependentAssembly>
Run Code Online (Sandbox Code Playgroud)

这是 Visual Studio 或 T4 模板引擎中的错误:https : //developercommunity.visualstudio.com/content/problem/358905/filenotfoundexception-systemruntime-version4210-wh.html

  • 对于 VS2022 .Net 6.0,我在这里找到了一个可行的解决方案/解决方法:/sf/answers/4254475641/。它涉及一个需要安装到 VS 中的扩展,该扩展可以解决 T4 的 bug 部分。源码在 GitHub 上。 (3认同)
  • 快速更新...他们没有修复 .Net Core 3.0 (2认同)
  • 对于 VS2022 Net6.0,这对我不起作用。然而。我可以自由地拥有我想要使用的 DLL 的源代码。我将使用的 DLL 项目支持到 .Net Framework 4.8。编译使用的项目。现在我的 T4 可以加载我的 DLL 并使用其中的内容。 (2认同)