Need a way to reference 2 different versions of the same 3rd party DLL
Solution 1:
It's achievable even if the two dll versions have the same public token.
Here the steps to achieve this:
- Ensure that the two version of the dll will be copied to the target directory
- Add the two dll's as content items of the project
- Enable local copy for both
- Ensure that the two version of the dll will be referenced at compile time
- Add the two dll's in the project as references
- Disable local copy for both
Just add the references is not enough, since only the newer one will be copied (even if you enable local copy for both). This give a project tree like this:
- Ensure that the two version of the dll can be distinguished at compile time
- Add an alias for at least on of the references
- Reference the libraries in the code using extern alias (see @drf response)
At this point you can compile but you still have problems at run-time. To fix those:
- Disable automatic binding redirection in the project
- Edit
app.config
to add anassemblyBinding
.-
assemblyIdentity
is the concerned dll. -
bindingRedirect
map a version range (oldVersion
) to a fixed version (newVersion
). -
codeBase
map a fixedversion
to a file path (href
).
-
bindingRedirect newVersion
and codeBase version
must match and match the version of the used dll.
Here, it's all about the dll assembly version, not the file version
Here is the program output:
This hack source code is available here.
Edit: As sharpiro commented, there is still a warning when the project is built, this is related to this msbuild bug for witch this answer is a workaround.
Solution 2:
This may be possible using the extern alias
feature. When you compile, include an alias to the DLL files, e.g.:
csc.exe ... /reference:AV1=v1.0.0.0/A.dll /reference:AV2=v2.0.0.0/A.dll
(This can be set in Visual Studio as well by changing the aliases
property of the reference.)
In the cs files you could use extern alias
to reference the namespaces:
extern alias AV1;
extern alias AV2;
// using statements
This allows you to reference each version independently:
var v1foo = new AV1::Foo();
var v2foo = new AV2::Foo();
For projects that use only one of the DLLs, you can include a reference to the desired version.
// ProjA cs file
extern alias AV1;
using Foo = AV1::Foo; // alternately, path to namespace
...
var foo = new Foo(); // from version 1 of library
// ProjB cs file
extern alias AV2;
using Foo = AV2::Foo; // alternately, path to namespace
...
var foo = new Foo(); // from version 2 of library
This allows both versions of the DLL to be referenced independently in the same solution. (MSDN Reference.)