-
Type: New Feature
-
Resolution: Won't Do
-
Priority: Unknown
-
None
-
Affects Version/s: None
-
Component/s: None
-
None
-
Dotnet Drivers
I have the following scenario:
[BsonKnownTypes(typeof(TopSection), typeof(FooterSection))] public record Section(string Type); [BsonDiscriminator("TopSection")] public record TopSection(string Type, string Title, string Description) : Section(Type); [BsonDiscriminator("FooterSection")] public record FooterSection(string Type, string Title, string Link) : Section(Type); [BsonDiscriminator("MiddleSection")] public record MiddleSection(string Type, string Title, int Views) : Section(Type); public record Page : IViewModel { [BsonId] public string Id { get; init; } public string Language { get; init; } public IEnumerable<Section> Sections { get; init; } = []; } public interface IReadonlyPageRepository : IReadonlyRepository<Page> { } public class Repository : ReadonlyRepository<Page>, IReadonlyPageRepository { public Repository(IMongoStoreFactory factory) : base(factory, "sections") { BsonSerializer.RegisterDiscriminatorConvention(typeof(Section), new ScalarDiscriminatorConvention("type")); } }
The Repository class is registered as Singleton and this code works properly in our api service. However, recently, we developed some integration tests using [WebApplicationFactory and TestServer|https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests] and problem arisen here.
WebApplicationFactory creates multiple instances of Repository and static method BsonSerializer.RegisterDiscriminatorConvention is called multiple times and this behaviour throws and exception.
Our best workaround by now is sorround this with an empty try/catch:
try { BsonSerializer.RegisterDiscriminatorConvention(typeof(Section), new ScalarDiscriminatorConvention("type")); } catch { }
Should be great if there would be a method in the BsonSerializer in order to check if there is already a DiscriminatorConvention already registered. BsonSerializer.LookupDiscriminatorConvention does not do his work here, because it adds a DiscriminationConvention by default ("_t").
Would it make sense to create a PR with a new method like:
BsonSerializer.TryToRegisterDiscriminatorConvention ??
- related to
-
CSHARP-3985 Support multiple SerializerRegistry(s)
- Backlog