lundi 7 juin 2021

Comparing type discovered through reflection with referenced type in .NET

End goal: I'm implementing a server application and protocol, and would like to allow for a plugin ability to handle any number of request commands. To do this, I am creating an interface in a dll (we'll call it IHandler). Other users will reference this and implement the interface to create their various handlers. For example: public class BlergHandler : IHandler

The dlls they create will be placed in a common directory, and at startup the server app will load all of the dlls through reflection. When a request comes in, it will spin up the required handler and pass on the request.

The problem I'm encountering is that I'm having trouble determining whether or not the types I find using reflection implement the interface or not. I believe the issue has to do with comparing the type interfaces loaded through reflection with a directly referenced interface. Here is the code I am using for the time being:

var DLL = Assembly.LoadFile(filename);

foreach (Type type in DLL.GetExportedTypes())
{
  // dynamic c = Activator.CreateInstance(type);
  if (!type.IsInterface)
  {
    Console.Write("Found: " + type.Name);
    if (type.GetInterfaces().Contains(typeof(IHandler)))
    {
      Console.Write("  : IHandler (contains check)");
    }
    
    if (typeof(IHandler).IsAssignableFrom(type))
    {
      Console.Write("  : IHandler (assignable check)");
    }
    Console.WriteLine(""); // For cleanliness
  }
}

The above checks fail even though the types found implement the interface in question. I also confirmed that if I directly reference the dll, the checks pass. e.g. TestHandler.GetInterfaces().Contains(IHandler) is true.

I hope I did a good job of explaining what I want to happen, and what is actually happening. I have to be missing something simple, but I'm stuck. Thanks in advance you glorious wizards!





Aucun commentaire:

Enregistrer un commentaire