user1448018
user1448018

Reputation:

Class instantiated from DLL does not seem to be implementing interface properly

I have a class I am attempting to instantiate through the use of Assembly and Activator, this class implements an interface, however when I run the instance of the class through a conditional that checks that the class implements it, I am getting false. What could be the problem?

My code where I am checking for implementation:

     string className = MyClass;
     Type type = null;
     Assembly assembly = Assembly.LoadFile("@C:\\MyDLL", new Evidence(AppDomain.CurrentDomain.Evidence));
     type = assembly.GetType(className);
     object instance = Activator.CreateInstance(type);

     //never makes it past this conditional
     if (!(instance is MyInterface)
     {
     //It always endsup in here, when it shouldn't.
     System.Writeline("ERROR");
     }
     else{
     //This is what needs to happen
     }

Code for the class MyClass that is outside the scope of all of this, and in MyDLL

public class MyClass: MyInterface
{
//Contents irrelevent to my problem
}

I am at a loss as to why this is not passing the conditional. Could I be instantiation the class wrong? Also to note I am a huge rookie when it comes to using Assembly/Activator and using interfaces.

Upvotes: 0

Views: 150

Answers (2)

Kit
Kit

Reputation: 21709

You may be referencing your assembly directly. If so, the types you load dynamically will have the identical name and namespace, but are considered different by the runtime.

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

Most likely reason - both DLL and your code have own version of MyInterface. This could happen either because

  • one did not want to spend time to come up with good unique name for interface,
  • someone decided to share interface as source instead of via assembly reference,
  • good named interfaces in the different namespaces and you are using the wrong one.

Upvotes: 3

Related Questions