Adding custom type converter to MongoDB in C#

I covered how to impelement a custom type converter for MongoDB in my previous article. In this article, I want to cover adding a serializer to MongoDB 'serializer'. There are couple of tricks you can use to make your life easier.

Unlike EF Core with its IEntityTypeConfiguration<TType>, MongoDB driver is more static. You can specify type converters using RegisterClassMap (which is static) or add it to the global Serializer Registry using RegisterSerializer. Personally, I prefer the latter. The idea of (potentially) having multiple underlying representations of the same object, like int or long for Bitrate, doesn't really float my boat. Either way, you will end up with static definition, either per class or global.

To register the type serializer you need to call BsonSerializer.RegisterSerializer

How can we ensure the register is called only once. Once solution would be to put all RegisterSerializers in StartUp.cs. This is a good solution for simple scenarios. For more complex solutions where code is shared is packed into a library or shared between multiple projects, I prefer to use a static constructor. It is a foolproof way of ensuring the code will execute irrespectively of the calling assembly and CLR will ensure the code will be execuded once.

You almost certainly want to be able to handle nullable values in your serializer - especially for value types. MongoDB driver has a NullableSerializer built-in. This is great because we don't need to implement another custom IBsonSerializer<Nullable<TType>>. Instread, we can reuse BitrateSerializer and wrap it around in a NullableSerilazer like so:

Leave a comment