动态加载的Type的SerializationException [英] SerializationException for dynamically loaded Type

查看:94
本文介绍了动态加载的Type的SerializationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于上一个问题(接口的XML序列化),我遇到了另一个问题...

As consequence of my previous question ( XML serialization of interfaces ) I obtained another problem...

我有一个从数据库导出数据的应用程序。导出过程由不同的具体类实现,这些具体类实现了用于调用的公共接口。

I have an application that export data from a database. The export procedure is implemented by different concrete classes that implement a common interface used for invocation.

具体实现是作为插件(DLL)加载的,所以我不

The concrete implementations are loaded as plug-ins (DLLs) so I don't reference them in my code directly.

我需要将这些具体类的实例作为字节数组序列化到数据库中,但是现在当我尝试从字节数组中反序列化它们时我得到一个 SerializationException:无法找到程序集…

I need to serialize instances of these concrete classes as byte arrays into my database, but now when I try to deserialize them from a byte array I obtain a SerializationException: Unable to find assembly …

我想它会出现是因为我在运行时用我的界面的具体实现...

I suppose it appens because I load at runtime the dll with the concrete implementation of my interface...

我该如何解决?

注意
我正在使用以下代码反序列化对象:

NOTE I'm using this code to deserialize objects:

    public static object DeSerialize(byte[] arrayToDeSerialize)
    {
        object serializedObject;
        using (MemoryStream stream = new MemoryStream(arrayToDeSerialize))
        {
            //Creating binary formatter to De-Serialize string.
            BinaryFormatter formatter = new BinaryFormatter();

            //De-Serializing.
            serializedObject = formatter.Deserialize(stream);
        }
        return serializedObject;
    }


推荐答案

您可以将 AppDomain.AssemblyResolve 事件可在需要时加载程序集。每次运行时需要无法解析的程序集时,都会引发该事件。它为您提供了在抛出无法找到程序集异常之前提供程序集的最后机会。示例在我链接的页面上。

You could hook the AppDomain.AssemblyResolve event to load the assemblies as they are needed. the event is raised each time that the runtime needs an assembly that it cannot resolve. It gives you one last chance to provide the assembly before the "Unable to find assembly" exception is thrown. Examples are on the page that I linked.

这篇关于动态加载的Type的SerializationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆