ASP.NET: FileLoadException when trying to use two different versions of the same dll

79 Views Asked by At

So i needed to use two different versions of the same dll in the same solution, which I managed to do by using extern aliases (Anybody trying to use two different versions of the same dll should try this solution ). Thing is, now I get this FileLoadException HRESULT: 0x80131040 as soon as my application starts running. Anybody know possible causes and/or solutions to this issue?

Yes, I had to change the name of one of the dlls, and no, just using the latter version is not possibility at this very moment.

1

There are 1 best solutions below

0
On

I managed to use two different version of same dll using appDomain. Its very clean and always work, but yes, it involve reflection and appDomain creation which are overheads in performance critical application. Here is how it can be done in console app, you can do the same in asp.net:

//Console app
using System;
using System.IO;
using System.Reflection;

namespace ConsoleApp1
{
class Program
{
    static System.AppDomain oldAssemblyDomain = null;
    static System.AppDomain newAssemblyDomain = null;

    static void Main(string[] args)
    {
        LoadOldVersion();
        LoadNewVersion();

        Console.ReadLine();
    }

    private static void LoadOldVersion()
    {
        oldAssemblyDomain = System.AppDomain.CreateDomain("oldAssemblyDomain", null);
        oldAssemblyDomain.DoCallBack(()=>{
            string dllName = "ClassLibrary1.dll";
            Assembly assembly = Assembly.LoadFile(Directory.GetCurrentDirectory() + @"\" + dllName);
            Type type = assembly.GetType("ClassLibrary1.Class1");
            MethodInfo minfo = type.GetMethod("SayHello", BindingFlags.Public | BindingFlags.NonPublic |
                      BindingFlags.Static | BindingFlags.Instance);
            var returnValue=minfo.Invoke(Activator.CreateInstance(type), null);
            Console.WriteLine(returnValue.ToString());
        });
    }

    private static void LoadNewVersion()
    {
        newAssemblyDomain = System.AppDomain.CreateDomain("newAssemblyDomain", null);
        newAssemblyDomain.DoCallBack(() =>
        {
            string dllName = "ClassLibrary2.dll";
            Assembly assembly = Assembly.LoadFile(Directory.GetCurrentDirectory() + @"\" + dllName);
            Type type = assembly.GetType("ClassLibrary1.Class1");
            MethodInfo minfo = type.GetMethod("SayHello", BindingFlags.Public | BindingFlags.NonPublic |
                      BindingFlags.Static | BindingFlags.Instance);
            var returnValue = minfo.Invoke(Activator.CreateInstance(type), null);
            Console.WriteLine(returnValue.ToString());
        });
    }
}
}


//Lib
namespace ClassLibrary1
{
public class Class1
{
    public static string SayHello()
    {
        return "Hello 1";
    }
}
}