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

Support IReadOnlyDictionary/ReadOnlyDictionary serialization

    • Type: Icon: New Feature New Feature
    • Resolution: Fixed
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: 2.5
    • Component/s: BSON, Serialization
    • Labels:
      None
    • Environment:
      .netstandard2.0
    • Minor Change

      IReadOnlyCollection & IReadOnlyList perform exactly as expected but their dictionary counterpart throws an exception on serialization. The concrete class ReadOnlyDictionary is able to serialize to the database but it throws an exception on deserialization.

      I've got it working in my codebase now it just feels like this should be supported out of the box.

      // Custom RO Serializer
      public class ReadOnlyDictionarySerializer<TKey, TValue> : DictionarySerializerBase<ReadOnlyDictionary<TKey, TValue>, TKey, TValue>
      {
          protected override ReadOnlyDictionary<TKey, TValue> CreateInstance() =>
              new ReadOnlyDictionary<TKey, TValue>(new Dictionary<TKey, TValue>());
      
          public override ReadOnlyDictionary<TKey, TValue> Deserialize(
              BsonDeserializationContext context, BsonDeserializationArgs args)
          {
              var dict = BsonSerializer.Deserialize<IDictionary<TKey, TValue>>(context.Reader);
              return new ReadOnlyDictionary<TKey, TValue>(dict ?? new Dictionary<TKey, TValue>());
          }
      }
      
      // Wire it up Globally to both the concrete class as well as the interface
      BsonSerializer.RegisterGenericSerializerDefinition(typeof(ReadOnlyDictionary<,>),
      	typeof(ReadOnlyDictionarySerializer<,>));
      BsonSerializer.RegisterGenericSerializerDefinition(typeof(IReadOnlyDictionary<,>),
      	typeof(ReadOnlyDictionarySerializer<,>));
      

            Assignee:
            vincent.kam@mongodb.com Vincent Kam (Inactive)
            Reporter:
            buvinghausen Brian Buvinghausen
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: