Assembly Independent Serialization in .NET

断了今生、忘了曾经 提交于 2019-12-18 05:54:18

问题


I use Serialization/DeSerialization Technique. BinaryFormatter class. Each time when new assembly is created the BinaryFormatter can't Deserialize binary data even if the class structure is the same, but the Assembly version differs. Is it possible to Deserialize binary buffer with no checking the assembly version if the class structure stays unchanged?


回答1:


Try this:

public sealed class CurrentAssemblyDeserializationBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        return Type.GetType(String.Format("{0}, {1}", typeName, Assembly.GetExecutingAssembly().FullName));
    }
}
formatter.Binder = new CurrentAssemblyDeserializationBinder();
formatter.Deserialize(inStream);

Thread Poster Added:

Yes, it works. Just make sure if any types of System.Generic or other Libs in the binary data are present, then you have to pass them through without changes. "ResizableControls" - old Assembly lib' name, "EntityLib" - new Assembly name. Also, the Version number is to be replaced as well, on demand.

public sealed class CurrentAssemblyDeserializationBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        string name;
        if (assemblyName.Contains("ResizableControl"))
        {
            name = Assembly.GetAssembly(typeof(EntityLib.Pattern)).ToString();
        }
        else
        {
            name = assemblyName;
        }
        return Type.GetType(String.Format("{0}, {1}",
            typeName.Replace("ResizableControl", "EntityLib"), name));
    }
}

Thanks, it is exactly what I needed.




回答2:


That is inherent with BinaryFormatter. There are some advanced things you can do to get around it (with surrogates etc), but it is not easy and I honestly don't recommend it.

I strongly suggest you look at a contract-based serializer; for example:

  • XmlSerializer
  • DataContractSerializer (but not NetDataContractSerializer)
  • protobuf-net

(I'm biased towards the last, as it gives a much more efficient output, and deliberately avoids a few more versioning issues)

In all those cases, the data storage does not (at least, with the default settings) include any knowledge of the types, except the contract as implied by the names, or as specified (typically in attributes).




回答3:


I think that is a know problem with BinaryFormatter - here is a possible solution you can controll which type to load with a SerializationBinder - the link provides code and an example how to use this (in almost all .net languagues)



来源:https://stackoverflow.com/questions/7154046/assembly-independent-serialization-in-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!