Recognizing interfaces while using reflection

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Big Daddy

    Recognizing interfaces while using reflection

    I have an interface called PeriodicJob. In a DLL, I declare the
    interface and then create a class that implements the interface. In a
    different executable, I also declare the interface. I then load the
    assembly with late binding and create an instance of the class with
    reflection. I try to cast the object to the class type of the
    interfact, but I get an invalid cast exception. It says that the
    object I am creating isn't a PeriodicJob. But the class does
    implement the PeriodicJob interface. I am guessing the reason it
    doesn't work is because when I declare the interface in the DLL and
    then declare it again in the EXE, even though they have the same name
    and structure, they are considered to be two different interfaces.
    Here's the code where I use reflection:

    Assembly a = Assembly.LoadFr om(path + "\\" +
    assemblyName);
    Object obj = a.CreateInstanc e(className);
    PeriodicJob pj = (PeriodicJob)ob j;

    How do I make it such that both the DLL and the EXE use the same
    actual interface? Do I have to declare the interface in a totally
    different DLL and then reference that DLL from both my EXE and DLL
    that has the implementation?

    thanks in advance,
    John
  • Marc Gravell

    #2
    Re: Recognizing interfaces while using reflection

    ..NET types are always scoped by their assembly. So yes; even if two
    projects use the same .cs file, they are two different .NET types, and
    cannot be cast to eachother. For runtime purposes, the trick is to
    place the code into an assembly that both of your *actual* assemblies
    can see. This might be a new dll, or it could just be that the exe
    references the dll (and place the interface in the dll).

    For serialization purposes, the best approach (for scenarios where it
    must be interoperable with different clients) is to use something that
    doesn't depend on .NET types - so BinaryFormatter might be
    inappropriate, but XmlSerializer / DataContractSer ializer / bespoke
    might be viable options.

    Marc

    Comment

    Working...