Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb driver - check if GuidSerializer is already registered

Tags:

c#

mongodb

I'm calling

BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.CSharpLegacy));

to register GuidSerializer as CSharpLegacy in global scope. If called more than once, this calls throws exception with the following message

  Message=There is already a serializer registered for type Guid.

Is there a way to check whether GuidSerializer is already registered? Would it make sense to unregister and re-register it again?

I know this error is expected, of course. I'm curious about confident (verified) approach to check if GuidSerializer is already registered before making such attempt.

The mongodb drvier version for C# is 2.11.4.

like image 505
Nesaje Avatar asked Oct 20 '25 17:10

Nesaje


1 Answers

Unfortunately, if you call GetSerializer, then a serializer is created and cached, unles one is already cached.

I think the only way to properly handle this, is to register a SerializationProvider instead of a serializer.

When the "serializer registry" creates a serializer for a type, it asks all the providers in turn if they support the type, and use the first one. So it doesn't really matter if you add the same provider 3 or 4 times.

class CsharpLegacyGuidSerializationProvider : IBsonSerializationProvider
{
    public IBsonSerializer GetSerializer(Type type)
    {
        if(type == typeof(Guid))
            return new GuidSerializer(GuidRepresentation.CSharpLegacy); 
            
        return null;
    }
}

// Register provider three times - no point, but proves it works and does not throw.
BsonSerializer.RegisterSerializationProvider(new CsharpLegacyGuidSerializationProvider());
BsonSerializer.RegisterSerializationProvider(new CsharpLegacyGuidSerializationProvider());
BsonSerializer.RegisterSerializationProvider(new CsharpLegacyGuidSerializationProvider());
    
var currentRepresentation = (BsonSerializer.LookupSerializer(typeof(Guid)) as GuidSerializer).GuidRepresentation;
Debug.Assert(currentRepresentation == GuidRepresentation.CSharpLegacy);

Now, if you serialize anything containing a Guid before you register this provider, it won't help, since the 'wrong' serializer will be cached in the registry.

like image 189
gnud Avatar answered Oct 23 '25 05:10

gnud



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!