Platform specific assembly resolve

Some time ago I had a situation where I needed to include a dependency within one of my web projects for which there existed only platform specific DLLs (x86 or x64, no AnyCPU version). The project itself was built and deployed as AnyCPU, and I had no intention of changing to platform specific 32bit and 64bit versions.

By attaching to the AppDomain.AssemblyResolve event, it is possible to provide your own method for locating and loading code to satisfy a given dependency. In this example the need was to substitute different platform specific copies of the same assembly depending on whether the process was launched in a 32 bit or 64 bit environment. However there is the opportunity to perform more complex implementations such as loading an assembly from a byte array or generating a dynamic assembly.

The AssemblyResolve event is fired whenever the runtime fails to resolve an assembly binding. Placing the platform specific assemblies outside the normal search path ensures that the event will be fired as soon as the runtime attempts to resolve the reference.
Attaching to this event provides the opportunity to locate and load assemblies using an alternative policy – in this case, one which selects the location according to whether the process is running as 32 bit or 64 bit.

For any assembly that cannot be found or loaded the event handler should simply return null. The runtime will continue to call any other attached handlers until one returns a value that is not null.

The code snippet below shows how you could load platform specific modules on demand in a web application.

If you’re thinking of implementing something similar in your own application, then it is worth referring to the following page for guidance and further links:

Leave a Reply