Search code examples
c#c++.netdll.net-assembly

How to address an assembly's dependency in C# when using Assembly.loadfrom()


I have created a C++ wrapper class library to import a C++ native dll. And I have added a project reference of this C++ class library to my C# application and copied all the dependencies to the Debug folder. So far every thing is working fine unless I want to do the same process for a an older version of that C++ native dll. Obviously I can't have two dll(s) with same name and also same name for the dependencies in a folder. So I decided to have a c# assembly wrapper for each version of c++ wrapper and have each assembly dll and it's dependencies in a separated folder.

Given that I can't use project reference any more because it needs the reference dll to be copied in a same folder of executable app, I tried to use Assembly.LoadFrom() to load the wrapper assembly on run-time and it loads the assembly but when it reaches to the Invkode line:

bject[] p = new object[] { command, null,format,handle};
uint ret= (uint) mi.Invoke(obj,p)

It throws an exception saying:

Could not load file or assembly 'MDVRCLib, Version=1.0.6110.25310, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

Once again if I use this assembly as a project reference and copy all it's dependencies to the project folder it will work fine. I am wondering while I am using Assembly.LoadFrom() to load the assembly from a different folder, how can I address the assembly's dependencies too, to prevent such an error?


Solution

  • You can attach to static AssemblyResolve event

    AppDomain.CurrentDomain.AssemblyResolve += (s, e) =>
    {
        //determine the required assembly using "e.Name"
        var filename = "....."; 
        return Assembly.LoadFile(filename)
    };