[CSHARP-655] Proposal: support multiple serialization contexts Created: 31/Dec/12  Updated: 06/Dec/21  Resolved: 06/Dec/21

Status: Closed
Project: C# Driver
Component/s: Serialization
Affects Version/s: 1.7
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Robert Stam Assignee: Unassigned
Resolution: Incomplete Votes: 2
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
duplicates CSHARP-3985 Support multiple SerializerRegistry(s) Backlog
Related
is related to CSHARP-635 Postpone creation of serializers unti... Closed

 Description   

Now and then someone proposes supporting multiple serialization contexts, as opposed to our current single global serialization context. This would allow you to serialize objects differently in different contexts.

For example, currently you might configure serialization of all DateTime values to use local date time as follows:

var defaultOptions = new DateTimeSerializerOptions(DateTimeKind.Local);
var dateTimeSerializer = new DateTimeSerializer(defaultOptions);
BsonSerializer.RegisterSerializer(typeof(DateTime), dateTimeSerializer);

However, this applies to all DateTimes globally, and there is currently no way to do this only in certain contexts (other than at a single property level when using class maps). If we supported multiple serialization contexts you might be able to code something like this instead:

var serializationContext = new SerializationContext();
var defaultOptions = new DateTimeSerializerOptions(DateTimeKind.Local);
var dateTimeSerializer = new DateTimeSerializer(defaultOptions);
serializationContext.RegisterSerializer(typeof(DateTime), dateTimeSerializer);
 
var databaseSettings = new MongoDatabaseSettings
{
    SerializationContext = serializationContext
};
var database = server.GetDatabase("test", databaseSettings);

and have the custom serialization context apply only to this one database. We would add similar properties to MongoServerSettings and MongoCollectionSettings to allow specifying a custom serialization context at those levels as well.

Of course, supporting multiple serialization contexts complicates lots of things. There are many places where we access the default global serialization context. Every one of those places could no longer assume the existence of a single global serialization context and would have to know which serialization context to use. This would require backwards breaking changes to many existing interfaces and classes (e.g. IBsonSerializer).

The purpose of this JIRA is to serve as a place to discuss the pros and cons of supporting multiple serialization contexts.



 Comments   
Comment by Robert Stam [ 06/Dec/21 ]

Closing this ticket because it applied to 1.x not 2.x.

See the very similar CSHARP-3985 ticket that applies to 2.x.

Generated at Wed Feb 07 21:37:27 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.