【发布时间】:2017-11-28 15:20:21
【问题描述】:
我正在为 .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 语句被颠倒,我的自定义约定将被找到并使用。为什么序列化程序不首先检查自定义对象鉴别器约定?
还有其他注册对象鉴别器约定的方法吗?还是覆盖默认约定?我需要编写自定义序列化程序吗?对于一个本来应该由默认序列化程序支持的功能来说,这似乎有点过头了。
请注意,这是一个库的一部分,我在设计时不知道哪些类类型将被持久化到数据库中。因此,我无法为更具体的类型注册约定。
【问题讨论】:
标签: c# mongodb .net-core mongodb-.net-driver