tags:

views:

129

answers:

1

Hi; Basically; I need to invoke a method on my WPF page, from a WPF frame where I load the WPF Page. I get the loaded page using Frame.Content property, and cast it to my page type since Content property returns Object type. The project builds successfully, however it throws InvalidCastException at runtime.

//This line throws InvalidCastException at runtime...
((PageA)TargetFrame.Content).methodA();

Here is the exception details:


[A]LoongNamespaceA.PageA cannot be cast to [B]LoongNamespaceA.PageA.
Type A originates from 'AssemblyA, Version=1.0.0.58, Culture=neutral, PublicKeyToken=null' in the context 'LoadFrom' at location 'C:\Users\abdullah.battal\AppData\Local\AssemblyA.dll'.
Type B originates from 'AssemblyA, Version=1.0.0.58, Culture=neutral, PublicKeyToken=null' in the context 'Default' at location 'C:\loongPathToSourceProject\bin\AssemblyA.dll'.

notice the context and location difference...

how can we solve this one?

A: 

Your class that is making the method call is expecting the assembly loaded into the default Context at 'C:\loongPathToSourceProject\bin\AssemblyA.dll'. The actual type being displayed was loaded from 'C:\Users\abdullah.battal\AppData\Local\AssemblyA.dll' into the LoadFrom context.

Since these types are from different assemblies on the disk, the type system recognizes them as different types and can not cast it to the type that you are doing the cast to (even if they have the same signature, .NET doesn't recognize them as the same as they came from a different context).

This article on MSDN describes that assemblies using LoadFrom have a few disadvantages, namely:

If an assembly is loaded with LoadFrom, and the probing path includes an assembly with the same identity but a different location, an InvalidCastException, MissingMethodException, or other unexpected behavior can occur.

You will probably want to rework how you are dynamically loading your assemblies.

Abe Heidebrecht
Yes, that seems like to be the problem here. But I got around it using reflection. Since both assemblies have the same signature, it didn't give error neither at compile-time nor at run-time. I was just curious why it didn't work previously. Thank you...
Abdullah Battal