我的任务是为应用程序创建一个新模块,因此,我要向项目添加新的 DLL。这一切都很好。
但是,在我的 DLL 中,我想使用外部 DLL 的新版本(我无法控制)。如果我只引用新的 DLL 并只使用那个 DLL,我的代码将工作,但旧代码将停止运行。
Could not load file or assembly 'itextsharp, Version=5.0.6.0, Culture=neutral,
PublicKeyToken=8354ae6d2174ddca' or one of its dependencies. The located assembly's
manifest definition does not match the assembly reference. (Exception from HRESULT:
0x80131040)
我试过一个简单的技巧来更改 DLL 的名称,但我认为这显然有点太天真了,认为它会奏效。我试过使用外部别名(通过在我的引用文献中定义它们),但我仍然不知道如何将两个同名文件放入一个 BIN 文件夹中......
我该怎么办?
最佳答案
假设您的项目结构如下:
...其中 A
和 B
是类库,C
是可执行类型的项目(例如单元测试或控制台项目)。
假设文件夹结构是这样的:
ABC.sln
A/A.csproj
A/...
B/B.csproj
B/...
C/C.csproj
C/...
lib/thirdparty4/thirdparty.dll
lib/thirdparty5/thirdparty.dll
如果我们试图天真地一起引用我们的项目,我们就会遇到问题:thirdparty.dll
的两个版本将被复制到同一个文件夹(输出(即 bin)目录C
)。我们需要一种方法让 C
将两个 dll 复制到它的输出目录,并提供一种引用其中任何一个的机制。
为了解决这个问题,我修改了 C.csproj
以包含以下内容:
<ItemGroup>
<Content Include="..\lib\thirdparty4\thirdparty.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Link>thirdparty4\thirdparty.dll</Link>
</Content>
<Content Include="..\lib\thirdparty5\thirdparty.dll">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<Link>thirdparty5\thirdparty.dll</Link>
</Content>
</ItemGroup>
这将指示它在其输出目录中创建 thirdparty4\thirdparty.dll
和 thirdparty5\thirdparty.dll
。
现在,在构建C
之后,它的输出目录如下所示:
C\bin\Debug\A.dll
C\bin\Debug\B.dll
C\bin\Debug\C.dll
C\bin\Debug\thirdparty4\thirdparty.dll
C\bin\Debug\thirdparty5\thirdparty.dll
为了指示 C
使用这两个 dll,我向其中添加了一个 App.config
文件,内容如下:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="thirdparty" culture="neutral" publicKeyToken="1234567890123445"/>
<bindingRedirect oldVersion="4.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
<codeBase version="4.0.0.0" href="thirdparty4\thirdparty.dll" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="thirdparty" culture="neutral" publicKeyToken="1234567890123445"/>
<bindingRedirect oldVersion="5.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
<codeBase version="5.0.0.0" href="thirdparty5\thirdparty.dll" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
这将指示程序集根据需要的版本使用一个 DLL 或另一个,这两个 DLL 都将在输出目录的子文件夹中可用。 (bindingRedirect 元素是可选的,但如果您需要对其应用一系列修订,则可以使用它们。)
关于c# - 使用同一 DLL 的多个版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5916855/