[CSHARP-2579] BsonSerializerRegistry does not distinguish between cached serializers and explicitly registered ones Created: 09/Apr/19 Updated: 27/Oct/23 Resolved: 02/May/19 |
|
| Status: | Closed |
| Project: | C# Driver |
| Component/s: | BSON, Serialization |
| Affects Version/s: | 2.8.0 |
| Fix Version/s: | None |
| Type: | Improvement | Priority: | Major - P3 |
| Reporter: | Dennis Janiak | Assignee: | Robert Stam |
| Resolution: | Works as Designed | Votes: | 0 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Environment: |
Windows |
||
| Description |
|
BsonSerializerRegistry.RegisterSerializer will just put the specified serializer into its internal cache, alongside other serializers that have been created by (default) providers before. If one tries to register a serializer for a type that has been looked up previously in the AppDomain, this will lead to an exception indicating that a serializer is already registered for the type. This can be especially confusing if there is only one call of the register method in the user's codebase. I would expect the explicit registration to override the default serializer; only throwing an exception if it has been registered explicitly before. In my use case, I use a library called Hangfire alongside my own code. Hangfire will always run before my code does, calling the MongoDB driver and filling the cache of the BsonSerializerRegistry with default serializers. Although it does not explicitly register global serializers itself, this will still clash with the serializer I want to register in my code, which I think it should not. Disclaimer: |
| Comments |
| Comment by Dennis Janiak [ 10/Apr/19 ] |
|
Thanks for your reply - thinking about it with a "fresh mind", this totally makes sense. The suggested change would be a potential source for really nasty bugs. As for me, this issue can be closed. Thanks! |
| Comment by Robert Stam [ 10/Apr/19 ] |
|
This behavior is by design. It is very important that your application use a single consistent representation for every type. If we allowed you to change the registered serializer at any time then there would be no consistent definition of how a document is serialized and deserialized. It makes no difference whether a serializer was explicitly registered by an application or implicitly registered the first time it was needed and not found. Registered is registered. Applications should completely configure the serialization register before any operations are performed against the database to make sure they register the desired serializers before implicit ones are registered instead. |