Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

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?

like image 707
joe Avatar asked Jan 27 '14 16:01

joe


2 Answers

TL;DR: Ig you are lazy, use BsonSerializer.LookupSerializer or BsonMemberMap.GetSerializer. To do it right, make sure the registration code is called once and only once.

The best approach to avoid this is to make sure the serializer is registered only once. It's a good idea to have some global startup code that registers anything that is global to the application once, and only once. That includes stuff like dependency injector configuration, tools like automapper and the mongodb driver. If you call this code only once and from a single point in code, you don't need to worry about thread safety, dead locks or similar troubles.

The MongoDB driver configuration settings are thread-safe, but don't assume that this is true for all software packages that you might need to configure. Also, locking can be very expensive performance wise if your code is multi-threaded, for instance in a web-application. Last but not least, that lookup you're doing might not be trivial in the first place, because some methods need to walk an entire inheritance tree.

like image 73
mnemosyn Avatar answered Nov 09 '22 05:11

mnemosyn


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 IBsonSerializationProviderand 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!

like image 41
Tugbay Atilla Avatar answered Nov 09 '22 05:11

Tugbay Atilla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!