dotnet / dotnet/orleans

Proposal: Allow users to opt-in to serializer behavior with parameterized object construction

Open
#7,964 1 comment 0 reactions 1 assignee Claimed by @ReubenBond View on GitHub
area-serialization
Dominant language
C#
Stars
10.9k
Forks
2.1k
Avg merge
14h 42m
Merged PRs (30d)
354

Description

It is common for developers to have initialization logic in class constructors, e.g. to pre-calculate some internal state that wasn't part of the serialized data.

Currently (v4), Orleans always pre-instantiates objects and lets users perform initialization logic through serialization callbacks. The primary motivation for this behavior is that it allows cyclic object graphs to be serialized.

To ease the migration path to Orleans, and to support a wider set of serialization scenarios, I propose that Orleans should be able to create objects by invoking a parameterized constructor. This allows classes to regain their original state after having been round-tripped through the serializer, without developers having to introduce specialized callback methods.

As part of the changes for #7937, Orleans now has an `OrleansConstructorAttribute`. This could be used to mark a specific constructor for Orleans to use during deserialization, allowing users to explicitly opt-in to the feature. Cyclic references would then not be supported, and it would be the users responsibility to ensure that objects don't reference themselves (directly or indirectly). Given the rarity of cyclic references and the opt-in nature of the feature I do not think that this is a concern.

To implement the feature, rules must exist on how parameters can map to fields and properties:
- calculate the canonical name by stripping leading underscores and lowercasing the first remaining character
- canonical names and types must match (except for parameters, which are allowed to be same-type-but-nullable)

Additionally, these would be the rules governing how objects are created:
- types with a single `OrleansConstructorAttribute` annotation opt-in to parameterized construction, all other types use the existing logic (the analyzer should be updated to warn if there are multiple annotated constructors for a single type)
- any fields or properties not mapped to a ctor parameter would be initialized as usual (after object creation)
- missing values for a required ctor parameter would result in a deserialization failure (exception), unless the parameter has been given a default value

If accepted, I volunteer to implement the required changes.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.