Answer a question

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.

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.

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐