[INFO] Exception Thrown When Trying To Deserialize An Object Whose Type Is Defined In An Assembly Which Is Loaded By Assembly.Lo

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

SYMPTOMS

Suppose you call Assembly.LoadFrom(...) to load an assembly named SimpleAsm in which type SimpleType is defined. Then you try to serialize a SimpleType ojbect, it works fine. But as soon as you deserialize some SimpleType object, you encounter following exception:

System.Runtime.Serialization.SerializationException: Cannot find the assembly SimpleAsm, Version=xxxx, Culture=xxxx, PublicKeyToken=xxxx.

Even the call to deserialization is in SimpleAsm itselft, the exception still exists. Although it looks a little bit ridiculous, it's the proper behavior by design.

CAUSE

"Some extensible applications use Assembly.LoadFrom to load an assembly and then construct objects from types defined in the loaded assembly. These objects can be serialized to a stream without any trouble. 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. In most cases, the Common Language Runtime (CLR) will not be able to locate the assembly file, causing a SerializationException exception to be thrown. "

RESOLUTION

Implement and register a System.ResolveEventHandler to help CLR class loader redirect to the properly position of the assembly and reload it into memory. The handler may look like this:

public static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)

{

string[] strProps = args.Name.Split(new char[] {','});

String strPath = m_codebase + strProps[0] + ".dll";

return Assembly.LoadFrom(strPath);

}

m_codebase is a relative directory that your assembly resides in. Before deserialize any SimpleType objects, register your event handler to the application domain:

Thread.GetDomain().AssemblyResolve += resolveHandler;

Also remember to unregister the handler when finish deserializing SimpleType objects to avoid any side-effects that may be brought by custom event handler:

Thread.GetDomain().AssemblyResolve -= resolveHandler;

MORE INFORMATION

.NET 247: SerializationException on microsoft.public.vsnet.ide

Run-time Serialization

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航