Binary Deserialization with different assembly version

荒凉一梦 提交于 2019-11-27 13:03:20

问题


I have a project which uses BinaryFormatter to serialize a collection of structs with string and bool? datatypes.

The serialization/deserialization works fine, however if I were to change the assembly which does the work it fails to deserialize because of the header in the binary file indicating that it requires Assembly x instead of Assembly y to handle the data.

Is it possible to setup the serialization/deserialization to be assembly agnostic?


回答1:


You can control how the binary formatter resolves its types by assigning a custom SerializationBinder to the formatter. In this way, you won't need to mess with the AppDomain's resolve events and you eliminate the risk of unexpected side effects from that.

There is a detailed example at MSDN.




回答2:


You can change your BinaryFormatter property AssemblyFormat to make serialization independent of assembly version.

// Example
var binFormat = new BinaryFormatter();
binFormat.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple;



回答3:


Hook into the AppDomain.OnAssemblyResolve event and fix-up the assembly names

private System.Reflection.Assembly OnAssemblyResolve( System.Object sender, System.ResolveEventArgs reArgs )
{
     foreach( System.Reflection.Assembly assembly in System.AppDomain.CurrentDomain.GetAssemblies() ) 
     {
         System.Reflection.AssemblyName assemblyName = assembly.GetName();
         if( assemblyName.FullName == reArgs.Name ) 
         {
              return( assembly );
         }
     }
}

source: http://osdir.com/ml/windows.devel.dotnet.clr/2003-12/msg00441.html




回答4:


There are altenative (binary) serialization engines (like this) that aren't assembly dependent.




回答5:


The GAC is your first resource, allowing different versions of the assembly to co-exist side-by-side. But that doesn't really solve anything unless your app is version tolerant too. Binary serialization has several features to handle version tolerant serialization. Read about it in this MSDN library article.



来源:https://stackoverflow.com/questions/505611/binary-deserialization-with-different-assembly-version

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