System.Web.Http中的向后兼容性损坏

时间:2016-05-13 10:24:56

标签: c# .net .net-assembly

我有一种情况,我在客户端应用程序中使用System.Web.Http.SelfHost.HttpSelfHostServer的一些代码,该程序集以.net4.0为目标,因此依赖关系是System.Web.Http.dll的v4.0.0.0

我在服务器上还有一些其他代码是webApi,目标是.net4.6.1。此程序集依赖于System.Web.Htpp.dll v5.2.3

一切都运行良好。

但后来我开始编写一个自动集成测试(作为单元测试),其中进程需要实例化系统的两​​个部分(没有IIS或类似的脚手架)。单元测试程序集必须是.net4.6.1(因为它依赖于服务器端程序集)。这意味着单元测试程序集中对System.Web.Http的引用会将v5.2.3带入其bin文件夹。

在运行时,这会产生ReflectionTypeLoadException LoaderException

"{"Inheritance security rules violated by type: 'System.Web.Http.SelfHost.HttpSelfHostConfiguration'. Derived types must either match the security accessibility of the base type or be less accessible.":"System.Web.Http.SelfHost.HttpSelfHostConfiguration"}"

在我的app.config中(对于单元测试程序集)我有一个运行时重做:

 <dependentAssembly>
    <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>

这意味着我的.net4依赖项被强制使用System.Web.Http的v5.2.3。

如果没有此运行时重定向,客户端程序集会抱怨缺少依赖项(System.Web.Http v4.0.0.0),如果我在bin目录中有System.Web.Http的v4.0.0.0(但是不是v5.2.3)然后服务器端程序集抱怨缺少依赖项。

有什么方法可以解决这个问题吗?对我而言,System.Web.Http v5.2.3似乎不向后兼容。

enter image description here

1 个答案:

答案 0 :(得分:2)

这比上面看起来简单得多。客户端代码是使用System.Web.Http.SelfHost.HttpSelfHostServer的代码,因此它将程序集System.Web.Http.SelfHost.dll拉入bin目录。

单元测试程序集正在拉入System.Web.Http.dll,因为它和服务器端都需要它。

selfhost dll是v4.0.0.0,system.web.http是v5.2.3。这是问题的来源。修复是为了确保System.Web.Http.SelfHost.dll的v5.2.3位于bin目录中,并将重定向添加到单元测试程序集的app.config中。