Search code examples
c#.net-corereflection

Use reflection to invoke methods in an assembly that contains a derived-class from the base-class that lives in another assembly


I have two projects/assemblies in a .NET Core solution.

  1. Project A contains a base-class called FooBase
  2. Project B contains a derived-class called FooDerived, as well as a bunch of other classes that I want to access via reflection

I've written some code in FooDerived in Project B so that when a certain call gets made, it uses reflection to find a certain class, finds a method within this class, and then calls that method. It's simple and it works great.

But NOW I want to refactor this code to the base class in Project A... while still using reflection to find the stuff in Project B.

Project B MUST reference Project A since FooDerived needs to know how to inherit from FooBase. Thus, Project A cannot reference Project B, which leads me to my question: how can I reference the types and methods using reflection in a project that I don't have a reference to?

To be concrete, here's some simplified code I currently have inside FooDerived in Project B that works correctly:

var type = Type.GetType("MyNamespace.MyClassName");

if (type == null) 
     throw new Exception();    

var methodInfo = type.GetMethod("MyMethod", BindingFlags.Public | BindingFlags.Static);

if (methodInfo == null) 
    throw new Exception();     

methodInfo.Invoke(null, null);
 

Thus, to summarize the question in the context of my code: when I migrate this code to Project A, it obviously can no longer find the types and methods in Project B, since they don't exist in Project A and no reference exists from Project A to Project B.

Is there some way to tell my base-class to reflect into the project where the derived class lives?


Solution

  • Actually the Type.GetType method requires an assembly-qualified name if the type is in another assembly, which means you need to specify the assembly name, this method can also accept a delegate to load the missing assembly.

    Assuming the type you want to load is in "ProjectB.dll", and the file is located in the working directory, you can do the following:

    var type = Type.GetType("MyNamespace.MyClassName, ProjectB",
        asmName => Assembly.LoadFrom($"{asmName.Name}.dll"), null);