We have a situation where we are using a 3rd-party DLL which is available in 32-bit and 64-bit versions. Our application could run as either 32-bit or 64-bit, so we had to make it load the correct version of the DLL.
The problem we had was that the 3rd-party DLL is a UI control, so you have to access it using the Windows Forms designer - which means you can't easily just use Assembly.LoadFrom()
to load it.
To fix this, we did the following:
- Work with the 32-bit DLL in the designer. (We had to do this because Visual Studio 2019 is 32-bit, so it couldn't load the 64-bit one.)
- Invent new filenames for the 32-bit and the 64-bit versions of the DLL. For example, "SomeDll32.dll" and "SomeDll64.dll". The important thing here is to ensure that these names are DIFFERENT from the DLL that you referenced in the designer.
- The installed application includes the renamed DLLs ("SomeDll32.dll" and "SomeDll64.dll" but NOT the one that was referenced in the designer.
If you were to try to run the application now, it would fail because it wouldn't be able to resolve the 3rd-party DLL that's referenced from the forms.
Here comes the actual fix to make it run the correct version:
- At the start of
Main()
attach to AppDomain.CurrentDomain.AssemblyResolve
.
- In the handler for
AssemblyResolve
check if the name of the DLL its looking for is the one that you have 32-bit and 64-bit versions of.
- If it is, substitute the correct name, depending on whether the app is running 32-bit or 64-bit.
For example here's what our code looks like for resolving a 3rd-party DLL used to display PDF files (using "PDFNet11").
In Main()
:
AppDomain.CurrentDomain.AssemblyResolve += pdfFNetResolveEventHandler;
Then in the event handler:
static Assembly? pdfFNetResolveEventHandler(object sender, ResolveEventArgs args)
{
if (!args.Name.StartsWith("PDFNet,"))
return null;
var dllPath = Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
Environment.Is64BitProcess
? "PDFNet64.dll"
: "PDFNet32.dll");
return Assembly.LoadFrom(dllPath);
}
It should be pretty obvious how this works. You should hopefully be able to do a similar thing.