C# Mongodb驱动程序-检查GuidSerializer是否已注册

C# Mongodb驱动程序-检查GuidSerializer是否已注册,c#,mongodb,C#,Mongodb,我打电话来 BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.CSharpLegacy)); 在全局范围内将GuidSerializer注册为CSharpLegacy。 如果多次调用,此调用将抛出异常,并显示以下消息 Message=There is already a serializer registered for type Guid. 有没有办法检查GuidSerializer是否已经注

我打电话来

BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.CSharpLegacy));
在全局范围内将GuidSerializer注册为CSharpLegacy。 如果多次调用,此调用将抛出异常,并显示以下消息

  Message=There is already a serializer registered for type Guid.
有没有办法检查GuidSerializer是否已经注册? 取消注册并重新注册是否有意义

当然,我知道这是意料之中的错误。我对自信(验证)的方法很好奇,这种方法可以在进行这种尝试之前检查GuidSerializer是否已经注册


C#的mongodb drvier版本是2.11.4。

不幸的是,如果调用
GetSerializer
,则创建并缓存序列化程序,除非已经缓存了一个序列化程序

我认为正确处理这个问题的唯一方法是注册一个
SerializationProvider
,而不是一个序列化程序

当“序列化程序注册表”为某个类型创建序列化程序时,它会依次询问所有提供程序是否支持该类型,并使用第一个。因此,添加相同的提供者3或4次并不重要

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);

现在,如果您在注册此提供程序之前序列化任何包含Guid的内容,它将不会有帮助,因为“错误”的序列化程序将缓存在注册表中。

。解释得很好。我喜欢。感谢您在注册提供程序之前提供有关序列化的说明。它确实发生在静态构造函数中,所以在执行任何其他操作之前。我遇到的问题是,静态构造函数被多次调用,因为该类是泛型的。