Mscorlib 无法找到抛出 FileLoadException 的依赖项

Mscorlib unable to find dependencies throwing FileLoadException

我有一个 webApi 项目抛出了无法找到 System.Diagnostics.DiagnosticSource 库的异常。我使用此文件添加了对 nuget 包的引用。但现在我得到:

System.IO.FileLoadException: 'Could not load file or assembly 'System.Diagnostics.DiagnosticSource, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)'

我在 "packages" 文件夹中的版本是 4.6.25519.03

我该如何解决这个问题?

csproj 参考:

    <Reference Include="System.Diagnostics.DiagnosticSource, Version=4.0.2.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
  <SpecificVersion>False</SpecificVersion>
  <HintPath>..\..\packages\System.Diagnostics.DiagnosticSource.4.4.1\lib\net46\System.Diagnostics.DiagnosticSource.dll</HintPath>
    </Reference>

Version 属性 不必 必须与该包的包文件夹中的版本号相匹配。事实上我的设置为

<Reference Include="System.Diagnostics.DiagnosticSource, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
  <HintPath>..\packages\System.Diagnostics.DiagnosticSource.4.5.0\lib\net46\System.Diagnostics.DiagnosticSource.dll</HintPath>
</Reference>

并且程序集上的产品版本设置为 4.6.26515.6,我在编译过程中没有收到任何错误或警告,并且在运行时找到了程序集。

我的建议是

  • 更新软件包(您使用的似乎是旧版本)。
  • 检查所有项目的其他引用版本。有时会有多个版本,因为有人在项目而不是解决方案级别管理包。
  • 检查其他 NuGet 包的依赖关系;它们可能引用了其他版本,这导致 .NET 程序集探测尝试加载错误的版本。您可以使用 AssemblyBinding Log Viewer 来尝试诊断此问题。另外,尝试更新这些包。

如果这些没有帮助,请考虑将 binding redirect 添加到您的 app.config 文件。