My app generates a new type Foo and writes it to new assembly. Then I create an object of type Foo and serialize it. If I delete the assembly and recreate it when I try to deserialize the Foo object it tells me that cannot convert type Foo to type Foo. It thinks those are different t开发者_StackOverflow中文版ypes. Is there a way to fix this?
EDIT: I have no control over the serialization.
EDIT: We found that the version guid is always different. What is this guid and how we can specify it?I think that the module version id (MVID) is written in the serialization when you use binary formatter. When you want to deserialize it searches for the type in assembly with that MVID. Here is the bad. You do not have control over MVID. Here is the good. You can open the dll file, find and replace the MVID with yours. I tested that by changing the MVID with hex editor and it works.
The way to fix it would be to use XML serialization instead of binary serialization. Binary serialization with BinaryFormatter emits type information and when the assembly is recreated it is no longer the same assembly (unless you ensure to have the exact same IL). Also if you are doing this in the same process (creating and deleting an assembly dynamically) note that because assemblies, once loaded, can never be unloaded from an AppDomain you might end up with the same assembly name loaded twice in the same AppDomain which is very bad and you will indeed have problems.
You are using BinaryFormatter
, right? there-in lies pain. Any contract-based serializer should be fine; XmlSerializer
, DataContractSerializer
, protobuf-net, JavaScriptSerializer
, etc.
Otherise, you'll have to handle the AppDomain.AssemblyLoad event and/or provide a custom binder; lots of work.
精彩评论