[CSHARP-587] Overwrite serializers in BsonSerializer Created: 02/Oct/12  Updated: 20/Mar/14  Resolved: 11/Oct/12

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

Type: Improvement Priority: Minor - P4
Reporter: Manuel Warum Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate
duplicates CSHARP-583 Allow Injection of custom primitive s... Closed

 Description   

It would be nice if there was a way to override default serializers for primitive types. While it can be worked around by registering serializers before the sctor of BsonSerializer executes or by using Reflection, a more straight-forward way would probably be to include a version of BsonSerializer.RegisterSerializer that allows to overwrite serializers for already covered types.

This stackoverflow question might be able to provide more context (note, I am not the original poster of said question): http://stackoverflow.com/questions/12201812/mongodb-override-default-serializer-for-a-c-sharp-primitive-type/12636123#comment17048789_12636123



 Comments   
Comment by Craig Wilson [ 11/Oct/12 ]

This works as designed.

Comment by Craig Wilson [ 02/Oct/12 ]

While I understand what you are saying, it isn't a good solution to enable changing the serializer for a type after it has already been used. For instance, if this was possible, the below sequence of events would be awkward.

  • save an entity with a double
  • change the double's serializer
  • read the entity with a double

Obviously, what would be read would be different than what was written, making the data un-uniform.

As Robert mentioned in the StackOverflow question, you can replace the default serializers for primitive types. The idea is that their is an implicit initialization phase for your applications, prior to any communication with MongoDB. In this initialization area, you can do virtually anything. The static ctor of BsonSerializer definitely runs prior to registration of new serializers (otherwise, .NET is broken). The reason Robert's suggestion works is because the defaults are part of a lazy serializer registration system (IBsonSerializabionProvider). Until a serializer for a type is needed, it isn't registered. Therefore, if you register a serializer for a type (e.g. double) before it is used, then you have replaced the defaults.

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