Search code examples
c#reflectiondll.net-assemblysystem.reflection

C# Load Assembly w/ Common References


I've run into a slight issue - I'm writing a program that loads DLLs, each of which contain a class which inherits from a class existing in a library referenced by both the loaded DLL and the "host" program that is loading the DLL. The issue here is that, when I try to load and cast to the superclass:

var assembly = Assembly.LoadFrom(dllPath);
var type = assembly.GetTypes().FirstOrDefault(x => x.IsSubclassOf(typeof (MySuperclass)));
...

Although both are referencing the class containing MySuperclass, since the dll is referencing the built class library (a separate file from the class library file the loading program is referencing) IsSubclassOf never returns true, because it considers the two classes to be different as they come from two different assemblies.

Furthermore, if you try casting a created instance of the loaded class to the superclass type, it can't do it since they're not the same (different assemblies).

So, my question is: how do you handle loading assemblies which reference common code, so that c# recognizes that you're loading a class which inherits from a common superclass?


Solution

  • You simply must use the same assembly files (even if they are identical) if you want programs to work together using common code. Here's how I solved the issue:

    The program is loading a DLL from a subdirectory of its own.

    Folder structure:

    MyApp Folder -->
         MyProgram.exe
         CommonDependency.dll
         Submodules ->
             MySubmodule.dll
    

    To get MySubmodule to use CommonDependency.dll within the next folder up, it's quite simple. Configure Visual Studio to not copy these dll dependencies to the build folder. Next, create an App.config in Visual Studio and add the following:

    <configuration>
      <runtime>
        <assemblyBinding>
          <probing privatePath="../"/>
        </assemblyBinding>
      </runtime>
    </configuration>
    

    This will tell the system to search for the assemblies in the parent folder ../ - if you want to have multiple folders, perhaps a separate dependency folder (relative to the location of the .dll) you can use ; as the delimiter - ../;../bin/; - the program will search these locations for the dependencies.