6

I need to reference a DLL which is available in 2 versions (one for 32bit and one for 64bit). My goal is to build an web application that works on both 32 and 64 bit systems.

I thought about referencing the 32bit assembly by default and using the AssemblyResolve event to load the 64bit version (if loading the 32bit version failed):

static void Main(string[] args)
{
    AppDomain.CurrentDomain.AssemblyResolve += _AssemblyResolve;
    // Try LoadAssembly ...
}

static System.Reflection.Assembly _AssemblyResolve(object sender, ResolveEventArgs args)
{
    var path = string.Format(@"...\lib_x64\{0}.dll", args.Name);
    return Assembly.LoadFrom(path);
}

But even when a BadImageFormatException occurs, the _AssemblyResolve handler will not be called. Is there any other way to achieve the proposed behavior?

ollifant
  • 8,576
  • 10
  • 35
  • 45

2 Answers2

1

Most straightforward way but less flexible from my point of view is explicitly specify platform specific references in csproj file using Condition:

<ItemGroup Condition=" '$(Platform)' == 'x86' ">
    <Reference Include="MyAssemblyx86">

Also you can do it dynamically using Assembly.Load(AssemblyName) method overload. Parameter is of type AssemblyName which exposes the property AssemblyName.ProcessorArchitecture which could be set to None, MSIL, X86, X64, IA64, AMD64

One thing you also could look into is the Publisher Policy File feature and command line argument /platform:processorArchitecture

sll
  • 61,540
  • 22
  • 104
  • 156
  • Using a condition within the project file only makes a distinction at build time. Thus, it would be still required to redistribute 2 different versions. – ollifant Sep 24 '11 at 12:20
  • The Assembly.Load solution would work, but this would require that I use lots of reflection. Or maybe dynamic would also be fine.. – ollifant Sep 24 '11 at 12:26
  • @ollifant : .NET Framework support two ways of assembly resolving - via static or dynamic reference. Dynamic referencing - Assembly.Load()/etc, static - referencing assembly through the project file or as dependency of an other reference via metadata. One thing you also could look into the `Publisher Policy File` feature and command line argument `/platform:processorArchitecture` – sll Sep 24 '11 at 13:16
0

See answers for dealing with this for System.Data.SQLite.

I think your proposed method should work but you need to move the 32-bit version so it can't be found by default, so _AssemblyResolve is always called for that dll. That's just a guess.

Community
  • 1
  • 1
Rory
  • 40,559
  • 52
  • 175
  • 261