Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-655

Proposal: support multiple serialization contexts

    • Type: Icon: New Feature New Feature
    • Resolution: Incomplete
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 1.7
    • Component/s: Serialization
    • None

      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.

            Assignee:
            Unassigned Unassigned
            Reporter:
            robert@mongodb.com Robert Stam
            Votes:
            2 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved: