Attention: We are retiring the ASP.NET Community Blogs. Learn more >

Assembly.LoadFrom and Serialization

For those that have followed my remoting woes, I, with the help of Wes, figured it all out today.  The issue was with deserialzing my structure arrays.  I am passing an array of structures to my remoted object.  I start my app with an exe that loads an assembly dynamically with assembly.LoadFrom.  I next use a type defined in the assembly, a form, to test my remoted object.

The array of structuress can be serialized to a stream problem free. However, when deserializing this stream, the formatter attempts to load the assembly by calling Assembly's Load or LoadWithPartialName method instead of calling the LoadFrom method again. In my case, the Common Language Runtime (CLR) was not be able to locate the assembly file, causing a SerializationException exception to be thrown.

I needed to implement a method whose signature matched the System.ResolveEventHandler delegate and then register this method with System.AppDomain's AssemblyResolve.  Now, whenever the formatter fails to load my assembly, the CLR calls into my ResolveEventHandler method. The identity of the assembly that failed to load is passed to this method. The method can extract the assembly file name from the assembly's identity and use this name to construct the path where the application knows the assembly file can be found. Then, the method can call Assembly.LoadFrom to load the assembly and return the resulting Assembly reference back from the ResolveEventHandler method.

Jeffrey Richter explains this well at:

http://msdn.microsoft.com/msdnmag/issues/02/04/net/default.aspx

which I paraphrase from in my above comments.

I strongly recommed anyone who is using Assembly.LoadFrom read Jeffrey's article to better understand what is happening with the CLR Loader when using assembly.Loadfrom and serialization with custom types.

Thanks Wes!

 

.
 

No Comments