You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级MailKit至v3.4.1遇System.Runtime.CompilerServices.Unsafe版本冲突

问题描述

此前使用MailKit 2.15版本,升级至v3.4.1后已自动安装包括System.Runtime.CompilerServices.Unsafe v4.5.3在内的所有依赖组件,但执行代码时抛出如下异常:

13-Oct-2022 16:33:19,303 [INFO ] Mail SendEmail       - System.IO.FileLoadException: Could not load file or assembly 'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'System.Runtime.CompilerServices.Unsafe, Version=4.0.4.1, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at System.Span`1..ctor(T[] array)
   at MimeKit.Utils.ValueStringBuilder..ctor(Int32 initialCapacity)
   at MimeKit.Utils.Rfc2047.Encode(FormatOptions options, Encoding charset, String text, Boolean phrase)
   at MimeKit.Header.EncodeUnstructuredHeader(ParserOptions options, FormatOptions format, Encoding encoding, String field, String value)
   at MimeKit.Header.EncodeAddressHeader(ParserOptions options, FormatOptions format, Encoding encoding, String field, String value)
   at MimeKit.Header.FormatRawValue(FormatOptions format, Encoding encoding, String value)
   at MimeKit.Header.SetValue(FormatOptions format, Encoding encoding, String value)
   at MimeKit.Header..ctor(Encoding encoding, HeaderId id, String value)
   at MimeKit.HeaderList.set_Item(HeaderId id, String value)
   at MimeKit.MimeMessage..ctor()

排查发现MimeKit依赖System.Memory,而System.Memory安装的是System.Runtime.CompilerServices.Unsafe v4.5.3,但运行时仍要求v4.0.4.1。升级前项目无该组件依赖。

原因分析

这是.NET程序集绑定重定向的典型问题:虽然安装了高版本的System.Runtime.CompilerServices.Unsafe,但项目中某个间接依赖的配置仍引用旧版本,导致CLR尝试加载旧版本,而实际找到的是高版本,版本不匹配触发异常。

解决方案

1. 添加程序集绑定重定向

在项目的app.config(桌面应用)或web.config(Web应用)中加入以下配置,让CLR将对旧版本的请求重定向到已安装的v4.5.3版本:

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" 
                          publicKeyToken="b03f5f7f11d50a3a" 
                          culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.5.3" 
                         newVersion="4.5.3" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

2. 强制统一依赖版本

右键项目 → 管理NuGet程序包,确认System.Runtime.CompilerServices.Unsafe的版本为v4.5.3;若存在版本冲突,可直接在项目文件(.csproj)中指定版本:

<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="4.5.3" />

3. 清理重建项目

  • 右键项目 → 清理
  • 删除项目目录下的bin和obj文件夹
  • 重新生成项目,确保所有依赖正确复制到输出目录

内容的提问来源于stack exchange,提问作者pradeep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 16:41:32