none
InvalidCastException using a 2nd AppDomain

    Question

  • Hi all,

    we are loading an instance of a class from a 3rd party assembly in a 2nd AppDomain. It contains a control which we host on a Form. Certain events are sent back into our assemblies for processing. Some of our DLLs also get laoded into the 2nd AppDomain.

    When an event is processed from the 2nd AppDomain we are getting an InvalidCastException when we are trying to cast between 2 of our own classes from our own assemblies.

    Unable to cast object of type 'xxxxxxx' to type 'xxxxxx'.

    I've spent a bit of time searching for an answer. I've seen similar posts in these forums and others. Based on these posts, I've tried all of the following without any success.

    1. We are using LoadFrom() to load the assembly. I've read that the same types from the same DLL aren't the same if they are loaded in different contexts. So I changed it to use Load()  using the assembly's strong name but that made no difference.

    2. I've used Process Explorer to make sure that both AppDomains are loading the same DLL's from the same location. ie. our DLLs that contain the class defintions.

    3. I've used Fusion Log Viewer to check if there are any loading issues but its not showing any problems.

    4. Tried handling the AssemblyResolver. Although I don't see how this helps as my assemblies are being found.

    Any other suggestions on what may be the problem ?

    Thanks,
    Anthony.

    Tuesday, June 18, 2013 1:01 AM

Answers

All replies

  • Hi Anthony,

    Welcome to the MSDN Forum.

    Can the type A can be casted to type B? Does them has inheritance relationship?

    Best regards,


    Mike Feng
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, June 19, 2013 2:12 AM
  • Hi Mike,

    Yes, Type A can be cast to Type B. There are many events (message handling) which get processed through that function where the type that is being cast from is Type A. If the current domain is the default AppDomain then there is no problem. It's only when an event is processed where the current domain is the 2nd AppDomain.

    As a test, I removed the 2nd AppDomain so that everything happened in the default domain and everything works.

    Anthony.

    Wednesday, June 19, 2013 4:43 AM
  • Hi Anthony,

    >>As a test, I removed the 2nd AppDomain so that everything happened in the default domain and everything works.

    If so, I think the cause is you didn't load all the related assembly into the second appdomain, so it doesn't work. 

    Best regards,


    Mike Feng
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Wednesday, June 26, 2013 1:02 AM