无法为对象设置自定义鉴别器约定

时间:2017-06-25 17:05:08

标签: c# mongodb .net-core mongodb-.net-driver

我正在使用.NET Core的MongoDB C#驱动程序(2.4.4)。 我想为所有对象注册一个自定义鉴别器约定:

BsonSerializer.RegisterDiscriminatorConvention(typeof(object), new CustomDiscriminatorConvention());

不幸的是,我的自定义鉴别器约定没有被序列化程序调用。我检查了BSON序列化器源代码,看起来在这种情况下总是使用默认的分层鉴别器约定。

https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Bson/Serialization/BsonSerializer.cs(第393-408行):

// inherit the discriminator convention from the closest parent (that isn't object) that has one
// otherwise default to the standard hierarchical convention
Type parentType = type.GetTypeInfo().BaseType;
while (convention == null)
{
    if (parentType == typeof(object))
    {
        convention = StandardDiscriminatorConvention.Hierarchical;
        break;
    }
    if (__discriminatorConventions.TryGetValue(parentType, out convention))
    {
        break;
    }
    parentType = parentType.GetTypeInfo().BaseType;
}

如果循环中的两个if语句将被反转,则可以找到并使用我的自定义约定。为什么序列化器不会首先检查自定义对象鉴别器约定?

是否有另一种注册对象鉴别器约定的方法?或者覆盖默认约定?我需要编写自定义序列化程序吗?对于一开始应该由默认序列化程序支持的功能,这似乎有些过分。

请注意,这是图书馆的一部分,我在设计时不知道哪些类类型将持久保存到数据库中。因此,我无法为更具体的类型注册约定。

0 个答案:

没有答案