[CSHARP-1837] Generic ICustomBsonTypeMapper with support for inheritance Created: 23/Nov/16  Updated: 03/Dec/20  Resolved: 03/Dec/20

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

Type: Improvement Priority: Minor - P4
Reporter: Aristarkh Zagorodnikov Assignee: Unassigned
Resolution: Won't Fix Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

Hello!

Currently, there is no driver-supported way to convert a generic type to a BsonValue in a custom way, because BsonTypeMapper.RegisterCustomTypeMapper BsonTypeMapper.TryMapToBsonValue uses a specific type. I would like to propose the ability to register custom type mappers by their corresponding types' generic template definition (in a separate dictionary) and making a two-pass check, first using a concrete type, and second – a type template.

Also, going up the inheritance chain when testing might be beneficial to allow for proper base class-related implementations. This of course will incur a performance hit, but considering that custom mapping is done right before failing out, I consider the impact of this possible performance being low.

This is going to help in situations like ours, where we have many primitive-based domain types, that inherit from a certain generic base class, but have the same basic inner representation. While automatic serialization via IBsonSerializers is wonderful, sometimes manual BsonDocument manipulation is warranted, and in this case we have to resort to extension methods that aid with BsonValue conversion, but this solution is clumsy and error-prone.

The generic template change is fully backwards compatible (if you don't take into account non-previously-working generic template registrations now working).
The inheritance change is not backwards compatible, but I do not believe that the scope of the change will have a significant impact on real existing code.



 Comments   
Comment by Aristarkh Zagorodnikov [ 30/Nov/16 ]

Thank you for the info about BsonTypeMapper being considered obsolete, Robert.
Unfortunately, our scenarios often involve manual BsonDocument creation. Well, it appears that we have to live with this and invent something to handle this for us. Maybe we should move to more automated BsonDocument generation.

Comment by Robert Stam [ 30/Nov/16 ]

This sounds like a reasonable request except for the fact that we consider the BsonTypeMapper to be obsolete. It is from an ancient time before serialization was added to the driver.

The proper way to convert an arbitrary POCO to a BsonDocument is to serialize it using a BsonDocumentWriter.

I'll leave this ticket open while we decide whether enhancing BsonTypeMapper in any way is the right thing to do.

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