Piyush Parashar
Piyush Parashar

Reputation: 874

OnSerializing/OnDerialized Methods Not Invoked for Child Class in Protobuf-net v3

I am trying to upgrade to protobuf-net version 3.2.26 from 2.2.1.

We have a custom code to allow (de)serialization of in case of inheritance relationship. For that purpose, a RuntimeTypeModel is created and the derived type and metatype information is added to the model. However, with version 3 the OnSerializing and OnDeserialized are not called if metatype.AddSubType method is called to add information of derived class. If we do not add type and metatype information then the methods are called but may lead to other serialization issues.

Here is the example:

    /*
         Example base and derived classes
    */
    [DataContract]
    [System.ComponentModel.TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
    [ProtoContract(SkipConstructor = true)]
    public class Demo : BaseDemo
    {
        [OnSerializing]
        protected override void OnSerializing(StreamingContext context)
        {
             //works only if overridden in derived class
        }
 
        [OnDeserialized]
        protected override void OnDeserialized(StreamingContext context)
        {
              //works only if overridden in derived class
        }
 
    }
 
    [DataContract]
    [System.ComponentModel.TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))]
    [ProtoContract(SkipConstructor = true)]
    public class BaseDemo
    {
         
        [OnSerializing]
        protected virtual void OnSerializing(StreamingContext context)
        {
 
        }
 
        [OnDeserialized]
        protected virtual void OnDeserialized(StreamingContext context)
        {
 
        }
    }

/*
Testing the class
*/

            string file = @"c:\Temp\test.proto";
 
            using (var fileStream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                // neither model or model2 work if metaType.AddSubType is called unless we override the method in child class
                var model = RuntimeTypeModel.Default;
                var model2 = RuntimeTypeModel.Create();
                var metaType = model.Add(typeof(BaseDemo), true);
                metaType.AddSubType(100, typeof(Demo));
                model.Serialize(fileStream, demo);
            }

Adding virtual methods is not an option as this will lead to breaking lot of consumers.

Any help is appreciated.

Upvotes: 0

Views: 30

Answers (0)

Related Questions