如何将程序集绑定重定向到当前版本或更高版本?

How do I redirect assembly binding to the current version or higher?

即使我的引用已将 Specific Version 设置为 false,我仍收到程序集绑定错误,因为目标机器具有更高版本。当某些目标计算机可能具有 1.61.0.0 版本而其他目标计算机具有 1.62.0.0 或更高版本时,如何指定当前版本或更高版本以避免出现以下错误?

System.IO.FileLoadException: Could not load file or assembly 'ServerInterface.NET, Version=1.61.0.0, Culture=neutral, PublicKeyToken=151ae431f239ddf0' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)
File name: 'ServerInterface.NET, Version=1.61.0.0, Culture=neutral, PublicKeyToken=151ae431f239ddf0'

您需要为绑定重定向添加一个 Web.config / App.config 密钥(请将版本更改为您实际需要的版本):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="ServerInterface.NET" publicKeyToken="151ae431f239ddf0" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

oldVersion 属性设置要重定向的版本范围。 newVersion 属性设置他们应该重定向到的确切版本。

如果您使用的是 NuGet,则可以通过 Add-BindingRedirect 自动执行此操作。 Here's an article explaining it

more information on binding redirects in general.

请看这里

Redirecting the binding in code 允许我使用任何版本。您可能想要做比这更多的检查,因为这会将任何失败的尝试重定向到具有相同名称的任何程序集。

public static void Main()
{
    AppDomain.CurrentDomain.AssemblyResolve += _HandleAssemblyResolve;
}

private Assembly _HandleAssemblyResolve(object sender, ResolveEventArgs args)
{
    var firstOrDefault = args.Name.Split(',').FirstOrDefault();
    return Assembly.Load(firstOrDefault);
}