[CSHARP-2154] Support IReadOnlyDictionary/ReadOnlyDictionary serialization Created: 25/Jan/18  Updated: 28/Oct/23  Resolved: 03/May/18

Status: Closed
Project: C# Driver
Component/s: BSON, Serialization
Affects Version/s: 2.5
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Brian Buvinghausen Assignee: Vincent Kam (Inactive)
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

.netstandard2.0


Issue Links:
Related
is related to CSHARP-1447 Serialization fails when implementati... Closed
Backwards Compatibility: Minor Change

 Description   

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<,>));



 Comments   
Comment by Vincent Kam (Inactive) [ 03/May/18 ]
  • Added support for ReadOnlyDictionary and IReadOnlyDictionary serialization
  • Deprecated DictionarySerializerBase's CreateInstance.
Comment by Githook User [ 03/May/18 ]

Author:

{'email': 'vincent.kam@10gen.com', 'name': 'vincentkam'}

Message: CSHARP-2154: Support ReadOnlyDictionary/IReadOnlyDictionary serialization
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/0934efbfa42736c95385376b7919d6ac31dcf268

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