jefffhaynes / BinarySerializer

A declarative serialization framework for controlling formatting of data at the byte and bit level using field bindings, converters, and code.
MIT License
290 stars 62 forks source link

IBinarySerializable - Access to the optional SerializationContext on serialization and deserialization #229

Open henbagle opened 9 months ago

henbagle commented 9 months ago

Hi!

I'm working on a project where I am trying to handle multiple versions of a binary format natively, so you could for example deserialize conforming to one version and reserialize to another, handle conversions gracefully. I'm passing in the version using the optional Context parameter upon deserialization, which works great most of the time doing things like the following:

public class BankStringUtf8
{
    [FieldOrder(0)]
    [SerializeWhen(nameof(BankSerializationContext.Version), 136,
        ComparisonOperator.LessThanOrEqual,
        RelativeSourceMode = RelativeSourceMode.SerializationContext)]
    public uint Length;
...

But when creating a custom class with IBinarySerializable, it appears that I have no way of accessing my version field to control the behavior. Through the BinarySerializationContext that gets passed in to the Serialize and Deserialize methods, I appear to have access to just about anything I could use for a [SerializeWhen] except for this serialization context. Is there an easy way to get access to this value when doing custom serialization?

So far I've been able to navigate around this by not using IBinarySerializable, but there are several instances where it would vastly cut down on code, subclasses, subclass factories, etc. by just using custom serialization. My version number gets serialized as part of the format, so it's accessible in theory, but it's nested pretty deep in the tree, and I can't do things like test smaller pieces to make sure they serialize properly without access to the version.