InfiniTec - Henning Krauses Blog

Don't adjust your mind - it's reality that is malfunctioning

InvalidCastException: Unable to cast object of Type 'X' to 'X'

In a recent project, the above exception was thrown when returning from a web service call. Interestingly, the exception was only thrown if the code was running within a web application. It would run fine when executed in an executable or even the Visual Studio development web server. At first I suspected some sort of permission problem but that couldn't really explain that particular error message. Next suspect was the shadow-copy feature of ASP.NET: The runtime does not actually run the assemblies from the path the IIS virtual directory points. Instead it copies all assemblies to the Temporary ASP.NET Files (C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files on x86 machines or C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files on x64 machines) and executes them from there. So I added two lines of code right before the exception would be thrown:

   1:  Trace.WriteLine(instance.GetType().Assembly.Location)
   2:  Trace.WriteLine(GetType(MyType).Assembly.Location)

Upon execution, the trace output was the following:

   1:  c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\c88143cc\98574940\assembly\dl3\98dad73b\f3cf1948_ddb4c801\MyAssembly.DLL 
   2:  C:\Development\TestApplication\MyAssembly.dll

This was the problem: One assembly was loaded from two different sources. What was the cause? Turns out that the first assembly was loaded because of an assembly reference. This way it was correctly placed in the Temporary ASP.NET Files. But the second instance of the assembly was loaded via reflection with a call to System.Reflection.Assembly.LoadFile. The solution is to use System.Reflection.Assembly.LoadFrom instead of the LoadFile method.

Why is this a solution? The main difference between LoadFrom and LoadFile is that LoadFrom goes through the normal Fusion bind process, thus allowing assembly redirection to happen. LoadFile on the other hand, just loads the assembly from the specified location.

For more information on this, see this blog posting from Suzanne Cooks blog.


Posted by Henning Krause on Tuesday, May 13, 2008 10:23 PM, last modified on Tuesday, November 30, 2010 12:19 AM
Permalink | Post RSSRSS comment feed

Comments (2) -

On 5/20/2008 10:17:54 PM Sasha Goldshtein Israel wrote:

Sasha Goldshtein

You might want to look at blogs.microsoft.co.il/.../...texts-Subtleties.aspx while recommending the use of Assembly.LoadFrom Smile

On 1/16/2009 5:27:55 PM zkc United Kingdom wrote:

zkc

I've tried several recipes like rinning IISRESET /RESTART, unifying all projects' build paths for a single bin\, setting "Local Copy" property of affected referencies to false, etc. ...all with no success.
And this is sorted my problem immediately.
Thanks indeed !!

 +Pingbacks and trackbacks (2)