c# - 复现 Newtonsoft.Json 程序集版本冲突

标签 c# json.net

我已经着手在 Newtonsoft.Json 中持续重现程序集版本冲突(与我之前的问题 Why is Newtonsoft.Json so prone to assembly version conflicts? 相关)以便更好地理解它,但我无法触发它。

从上面的答案来看,如果我有一个引用一个版本的 Json.NET 的项目 A,然后它引用一个本身引用不同版本的项目 B(并且它们没有程序集重定向来处理问题)。

我已经用一个类库项目和一个命令行项目创建了一个解决方案,这两个项目都引用了 Newtonsoft.Json,我为这两个项目安装了 Nuget 包管理器,然后我编辑了类库 packages.config 以使用旧版本:

<package id="Newtonsoft.Json" version="6.0.1" targetFramework="net452" />

虽然命令行项目引用了最新版本:

<package id="Newtonsoft.Json" version="10.0.2" targetFramework="net452" />

这不会触发问题,但是,项目仍然成功构建并执行(我只是序列化一个字符串并从两个项目打印它,我从 EXE 调用 DLL 以确保它尝试加载两个版本的 Newtonsoft .Json.

我已经在 https://github.com/sashoalm/ReproduceNewtonsoftJsonBug 上传了测试项目如果需要的话。

为什么没有触发错误?

最佳答案

首先,尽管 packages.json 文件说了什么——您的控制台应用程序引用版本 6,而不是 10:

<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
  <HintPath>..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>

但是,如果您修复该问题(例如通过卸载并重新安装软件包)- 它仍然可以正常工作。这是因为在这种情况下存在自动绑定(bind)重定向,请参阅 here :

Starting with Visual Studio 2013, new desktop apps that target the .NET Framework 4.5.1 use automatic binding redirection. This means that if two components reference different versions of the same strong-named assembly, the runtime automatically adds a binding redirection to the newer version of the assembly in the output app configuration (app.config) file.

如果您查看输出 ConsoleApp5.exe.config 文件(不是 app.config 在 Visual Studio 中,而是在 Debug\Release 文件夹中)- 您会注意到绑定(bind)重定向被自动添加到那里:

<runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
      <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
      <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
    </dependentAssembly>
  </assemblyBinding>
</runtime>

如果您删除它们然后运行目标 exe - 它会在运行时失败。

自动绑定(bind)重定向由 .csproj 文件中的属性控制。如果您打开控制台应用程序 .csproj,您将在其中一个 PropertyGroup 中看到:

<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>

如果您将 true 更改为 false - 您将禁用此功能并会看到您试图重现的警告。

关于c# - 复现 Newtonsoft.Json 程序集版本冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44675418/

相关文章:

c# - 使用 JSON.NET 递归地解析未知的 JSON 结构

c# - 依赖于访问修改后的闭包的实现是否不可取?

c# - 自定义授权过滤最小 API .Net 6

c# - Azure移动应用程序自定义json序列化

json - NewtonSoft JsonConvert - 反序列化一个看起来像 { “@nil” : “true” } 的 JSON 对象

c# - JSON.net 缺少属性的默认值

mongodb - 是否可以在没有 "$"的情况下在 JSON.Net 中获得多态反序列化?

c# - EPPlus 配方评估

c# - Visual Studio 错误 : Unrecognized Guid format

c# - 在asp.net和java之间共享 session 变量