并排装配加载问题

时间:2013-02-19 08:16:42

标签: c# .net reflection

我有一个简单的应用程序,它在运行时通过这段代码从2个子文件夹加载两个程序集:

Assembly.Load("A, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
Assembly.Load("B, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");

目录结构是:
enter image description here
因此预期的负载如下:

TheApp.exe -> A.dll -> C.dll (version 2.0.0.0)
           -> B.dll -> C.dll (version 1.0.0.0)

请注意C.dll已签名,因此两个版本应并排加载。

为了确保应用程序从正确的位置加载程序集,我将以下内容添加到应用程序配置文件中:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="B;A" />
    </assemblyBinding>
  </runtime>
</configuration>

问题是应用程序在启动时会崩溃并显示以下消息:

=== Pre-bind state information ===
LOG: User = ...
LOG: DisplayName = C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=93a02044a09d059a
 (Fully-specified)
LOG: Appbase = file:///D:/Temp/TheApp/bin/Debug/Test/
LOG: Initial PrivatePath = NULL
Calling assembly : A, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null.
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: D:\Temp\TheApp\bin\Debug\Test\TheApp.exe.Config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v2.0.50727\config\machine.config.
LOG: Post-policy reference: C, Version=2.0.0.0, Culture=neutral, PublicKeyToken=93a02044a09d059a
LOG: Attempting download of new URL file:///D:/Temp/TheApp/bin/Debug/Test/C.DLL.
LOG: Attempting download of new URL file:///D:/Temp/TheApp/bin/Debug/Test/C/C.DLL.
LOG: Attempting download of new URL file:///D:/Temp/TheApp/bin/Debug/Test/B/C.DLL.
WRN: Comparing the assembly name resulted in the mismatch: Major Version
ERR: Failed to complete setup of assembly (hr = 0x80131040). Probing terminated.

问题:为什么运行时仅查看“B”文件夹?为什么不继续在A文件夹中查找正确版本的共享程序集?

EDIT1 :我添加了<codeBase>标记,如下所述,我知道在我的配置文件中有以下内容:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
       <probing privatePath="B;A" />
    </assemblyBinding>
    <dependentAssembly>
       <assemblyIdentity name="C" publicKeyToken="93a02044a09d059a" /> 
       <codeBase version="1.0.0.0" href="B/C.dll"/>
       <codeBase version="2.0.0.0" href="A/C.dll"/>
    </dependentAssembly>
  </runtime>
</configuration>

但问题仍然存在!

1 个答案:

答案 0 :(得分:6)

请参阅有关探测的this MSDN页面上的说明,该说明直接解决了您的问题:

  

如果目录中有多个版本的程序集,并且要引用该程序集的特定版本,则必须使用<codeBase>元素而不是{{1}的privatePath属性元素。如果使用<probing>元素,则运行时会在第一次找到与引用的简单程序集名称匹配的程序集时停止探测,无论它是否正确匹配。如果是正确的匹配,则使用该组件。如果它不匹配,则探测停止并且绑定失败。

运行时正在寻找2.0.0.0版本但找到1.0.0.0版本并停止查找。

最终解决方案是将配置文件更改为以下内容:

<probing>