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

时间:2015-07-06 21:08:36

标签: c# .net app-config assembly-binding-redirect

即使我的引用已将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'

2 个答案:

答案 0 :(得分:12)

您需要为绑定重定向添加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.

答案 1 :(得分:2)

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);
}