Search code examples
c#serializationstrongname

Can strong naming cause problems with object serialization in C#?


I serialize some configuration objects and store the result bytes within a database.

new BinaryFormatter().Serialize(memoryStream, instance);
Convert.ToBase64String(memoryStream.ToArray());

These objects will be deserialized later.

new BinaryFormatter().Deserialize(memoryStream);

It's possible, that the Application has some new assembly versions at the time of deserialization. In general it works well, but sometimes I get a file load exception: "The located assembly's manifest definition does not match the assembly reference.". The assemblies work all with strong naming, can that be the problem and how could I avoid this problem?

Thanks for help


Solution

  • Absolutely, using BinaryFormatter with database (i.e. long-term) storage is a bad idea; BinaryFormatter has two three big faults (by default):

    • it includes type metadata (shucks if you move/rename your types... this can mean strong name/versioning too)
    • it includes field names (fields are private details!)
    • it is .NET specific (which is a pain if you ever want to use anything else)

    My blog post here raises two specific issues with this - obfuscation and automatically implemented properties... I won't repeat the text here, but you may find it interesting.

    I recommend the use of a contract based serialization. XmlSerializer or DataContractSerializer would suffice normally. If you want small efficient binary, then protobuf-net might be of interest. Unlike BinaryFormatter, the binary from this is portable between implementations, extensible (for new fields), etc. And it is quicker and smaller, too.