CSDN博客

img dexi

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

发表于2004/6/23 0:07:00  620人阅读

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

0 0

相关博文

我的热门文章

img
取 消
img