How do I detect whether a mongodb serializer is already registered?

mongodb

Solution

If you are using

BsonSerializer.RegisterSerializer(typeof (Type), typeSerializer);

you might get this error "there is already a serializer registered for type". Because you cannot register the same type of serializer 2 times. But you can write your own serializer and this serializer will work before default serializers.

For instance: if you want to use local `DateTime` instead of Utc which is default.

all you need to do is that writing a class implementing `IBsonSerializationProvider`and register this provider to `BsonSerializer` as soon as possible!

here is the sample code.

public class LocalDateTimeSerializationProvider : IBsonSerializationProvider
{
    public IBsonSerializer GetSerializer(Type type)
    {
        return type == typeof(DateTime) ? DateTimeSerializer.LocalInstance : null;
    }
}

and to be able to register

BsonSerializer.RegisterSerializationProvider(new LocalDateTimeSerializationProvider());

I hope this helps, you can also read the original documentation in here this .net driver version of mongodb is 2.4!

Problem

I have created a custom serializer for mongoDB. I can register it and it works as expected. However the my application sometimes throws an error because it tries to register the serializer twice. How do I detect whether a serializer has already been registered and thus stop my application from registering a second time?

Original source