[CSHARP-4835] Support BsonKnownTypes attribute on interface types Created: 05/Nov/23  Updated: 14/Nov/23

Status: Backlog
Project: C# Driver
Component/s: None
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Henry Yu Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

`System.Text.Json` can support polymorphic JSON serialization/deserialization using an interface as base type. I think MongoDB should support `BsonKnownTypes` attribute on interface types as well.



 Comments   
Comment by Boris Dogadov [ 09/Nov/23 ]

Hi henry@schedgo.com ,

This is a good point. We will be investigating this use case further.

Please follow this ticket for further updates.

Comment by Henry Yu [ 09/Nov/23 ]

Hi boris.dogadov@mongodb.com!

That does work! However, I would prefer a descriptive way of doing it since I build class libraries for downstream packages to consume. I would not want consumers to need to imperatively call some methods to register types that they do not own or put some startup code in a static constructor that could slow down startup of downstream executables.

Henry{}

Comment by Boris Dogadov [ 09/Nov/23 ]

Hi henry@schedgo.com 

For interfaces serialization, driver specifies the concrete type discriminator, which is used for deserializing as well.
One thing to remember is to register the concrete type with object serializer allow list. Example:

          public interface IMyInterface
          {
              public int IntField { get; set; }
          }
 
          public class A : IMyInterface
          {
              public int IntField { get; set; }
          }
 
          var objectSerializer = new ObjectSerializer(t => ObjectSerializer.DefaultAllowedTypes(t) || t == typeof(A));
          BsonSerializer.RegisterSerializer(objectSerializer);
 
          IMyInterface obj= new A() { IntField1 = 1234 };
          var json = obj.ToJson();
          var obj2= BsonSerializer.Deserialize<IMyInterface>(json);

Please let us know if this addresses your question, or is there any other scenario which is not supported by driver.

Comment by PM Bot [ 05/Nov/23 ]

Hi henry@schedgo.com, thank you for reporting this issue! The team will look into it and get back to you soon.

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