0

I have 2 dlls, one with an interface and another that actually uses the interface. I can call the 2nd dll using reflection, but I wanted to know if I can get more information about it using the interface.

I have something like...

// the interface dll
namespace Mynamespace{
  public interface Interface1
  {
    int Add( int a, int b);
  }
}

and another interface in the same dll...
note that it is derived from the first one.

namespace Mynamespace{
  public interface Interface2 : Interface1
  {
    int Sub( int a, int b);
  }
}

I then call a method using reflection

// get the 2 interfaces
var asm = Assembly.LoadFile( dllInterfacePath);
var type1 = asm.GetType("Mynamespace.Interface1");
var type2 = asm.GetType("Mynamespace.Interface2");

// get the main class
var asmDll = Assembly.LoadFile( dllPath);
var type = asmDll.GetType("MyMS.SomeClass");

// create an instance
var instance = Activator.CreateInstance( type, null );

Now my question is how can I tell if the instance created is derived off Interface2 or Interface1, I could look for method "Sub(...)" and if it is not present then I know it is of type Interface1.

But I was wondering if there was a better function to dynamically achieve this?

I cannot use

typeof(Interface1).IsAssignableFrom(typeof(MyMS.SomeClass));

as both Interface1 and MyMS.SomeClass are dynamically loaded and not referenced in the project.

FFMG
  • 1,208
  • 1
  • 10
  • 24

1 Answers1

3

You don't have to use the typeof to have a type reference, the reflection API works well for dynamically loaded types, too.

Sorry, but it does not work. typeof(Interface1).IsAssignableFrom(typeof(MyMS.SomeClass)); or type.IsAssignableFrom(type1); does not work

It does work but by calling LoadFile you are basically loading the same interface assembly twice, thus making it impossible to refer to the same interface type on the class that implements it:

https://blogs.msdn.microsoft.com/suzcook/2003/09/19/loadfile-vs-loadfrom/

Just replace LoadFile with LoadFrom or even ReflectionOnlyLoadFrom:

I just recreated your scenario, I have an assembly with the interface and another assembly with the implementation.

Assembly interfaceLib      = Assembly.ReflectionOnlyLoadFrom( "InterfaceLib.dll" );
Assembly implementationLib = Assembly.ReflectionOnlyLoadFrom( "ImplementationLib.dll" );

var i = interfaceLib.GetType( "InterfaceLib.Interface1" );
var t = implementationLib.GetType( "ImplementationLib.Class1" );

var b = i.IsAssignableFrom( t );

Console.WriteLine( b );

// prints "true"

If I switch to LoadFile I get false.

Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
  • The ``LoadFile`` vs ``LoadFrom`` was the issue, the subtle, (yet important), difference between the two is not immediately obvious if you are not looking for it. – FFMG Apr 25 '16 at 17:10