【问题标题】:Cannot set custom discriminator convention for object无法为对象设置自定义鉴别器约定
【发布时间】: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


    【解决方案1】:

    我们正在使用的解决方法是注册一个普通约定,将鉴别器设置为我们想要的:

    public class CustomDiscriminatorConvention : ConventionBase, IClassMapConvention
    {
        public void Apply(BsonClassMap classMap)
        {
            Type type = classMap.ClassType;
            if (type.IsClass
                && type != typeof(string)
                && type != typeof(object)
                && !type.IsAbstract)
            {
                classMap.SetDiscriminator(GetCustomDiscriminatorFor(type));
            }
        }
    }
    

    要注册约定,请在您的应用启动时使用以下内容:

    var conventions = new ConventionPack { new CustomDiscriminatorConvention(), ... };
    ConventionRegistry.Register("Custom conventions", conventions, t => true);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-04
      相关资源
      最近更新 更多