Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protobuf .NET Post Deserialization Handler

Is there a way to handle an event or call back into an object that has just been deserialized by Protobuf without having to explictly make call the method from the deserialized object?

For example, say I have the following class:

[ProtoContract]
public class Customer
{
    [ProtoMember(1)]
    public string FirstName { get; set; }

    [ProtoMember(2)]
    public string MiddleName { get; set; }

    [ProtoMember(3)]
    public string LastName { get; set; }

    [ProtoMember(4)]
    public Dictionary<int, string> Addresses { get; set; }

    public Customer()
    {
        //Subscibe to a Protobuf deserialization complete event?
    }

    public void ValidateAddresses()
    {
        //Some routine to validate addresses
    }
}

Would there be a way to call into "ValidateAddresses" without having to call it explicitly from the deserialized object in the code block where it was deserialized? Calling it in the constructor is worthless because Protobuf hasn't applied the serialized values yet so it would be nice to have a way to know when it has finished applying the values. I'm hoping there is a way to accomplish this in order to eliminate the need to refactor the post deserialization call everywhere that the object is being used.

I have some ideas but I figured I would post the question before I head down the path of proofing them out in case someone has a better one that I'm just not seeing yet (which is very likely). Thanks in advance.

like image 553
Ryan Avatar asked Feb 12 '13 17:02

Ryan


1 Answers

Yes. Protobuf-net supports standard serialization callbacks. Either via the WCF / DataContractSerializer attributes, or the protobuf-net specific ones. Specifically, you ca mark a method with either [OnDeserializedAttribute] or [ProtoAfterDeserialization], and it will be invoked at the end of deserialization. Methods can be invoked before serialization, after serialization, before deserialization and after deserialization.

WCF requires a specific signature for these methods, but protobuf-net is less fussy: it will work with the WCF signature, but will also allow parameterless methods, or any combination of the usual parameters, or protobuf-net's own serialization context.

like image 165
Marc Gravell Avatar answered Sep 23 '22 02:09

Marc Gravell