anerjan / protobuf-net

Automatically exported from code.google.com/p/protobuf-net
Other
0 stars 0 forks source link

Parameterless constructors and passing a parameter on deserialization #351

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
There is a problem with parameterless constructors being used during 
deserialization.
Suppose, we are building an object graph to be serialized later. We are using a 
parameterless constructor in one of the classes to perform our initialization. 
It is not immediately apparent, that the same constructor will be used to 
deserialize the object, which may lead to subtle bugs.
To prevent this, we could introduce a meaningless parameter into the main 
constructor, leaving the deserializing constructor empty. However, this is 
counterintuitive and cumbersome.

This leads to the second issue. It would be rather useful to allow passing a 
parameter into the deserializer- then, each object in the graph would be 
deserialized using a constructor, that receives this type of parameter.

What would be your approach at tackling these two issues?

Original issue reported on code.google.com by symboli...@gmail.com on 18 Jan 2013 at 3:22

GoogleCodeExporter commented 9 years ago
There are lots of options here:

- constructors are *optional*, and can be completely disabled with the 
SkipConstructor instruction on ProtoContract, or via the RuntimeTypeModel
- there is full support for deserialization callbacks, both before and after 
deserialization - using the standard attributes or protobuf-net specific 
attributes
- you can also supply your own type-factory on a per-type basis

Any of those help?

Original comment by marc.gravell on 18 Jan 2013 at 4:02

GoogleCodeExporter commented 9 years ago
- Indeed, constructor optionality is quite handy. Except, disabling the 
constructor also disables field initalization, it seems.
- The callback method attributes are useful as well, only, they are also 
parameterless, as far as I know.
- Factories could be a viable option, but I didn't find any information on how 
to pass them context information.

Original comment by symboli...@gmail.com on 18 Jan 2013 at 4:25

GoogleCodeExporter commented 9 years ago
callbacks and factory methods both optionally take the serialization context as 
parameters; either the regular framework ones, or the specific pb-net context. 
IIRC, TypeModel.Deserialize accepts the context, but if not: ProtoReader 
definitely does. I'm not at a PC, but I can prepare and example later. Any 
preference between the two?

Original comment by marc.gravell on 18 Jan 2013 at 4:37

GoogleCodeExporter commented 9 years ago
Thank you, this should do the trick. TypeModel.Deserialize does, indeed, have a 
SerializationContext parameter.
The example won't be necessary, at least for me.

Original comment by symboli...@gmail.com on 18 Jan 2013 at 4:47