为所有继承自基本类型的 类 设置自定义 MongoDB BsonSerializer

Setting custom MongoDB BsonSerializer for all classes which inherit from base type

有没有办法为从特定基类型继承的所有类型设置自定义序列化程序?

给定以下类型:

class Identity<T> {
    T Value { get; set; }
}
class StringIdentity : Identity<string> {
}
class PersonIdentity : StringIdentity {
}

使用以下型号:

class Person {
    public PersonId Identity { get; set; }
}

以及以下序列化程序:

class StringIdentitySerializer : IBsonSerializer<StringIdentity>
{
    object IBsonSerializer.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return Deserialize(context, args);
    }

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, StringIdentity value)
    {
        context.Writer.WriteString(value.Value);
    }

    public StringIdentity Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        return new StringIdentity(context.Reader.ReadString());
    }

    public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
    {
        Serialize(context, args, value as StringIdentity);
    }

    public Type ValueType => typeof(StringIdentity);
}

我认为 BsonSerializer.RegisterSerializer(typeof(StringIdentity), new StringIdentitySerializer()); 会在 Person 上将我的 属性 Id 作为字符串序列化。

当我将 Id 属性 更改为 StringIdentity.

类型时,此序列化程序起作用

我理解为什么会发生这种情况(PersonIdentityStringIdentity 不是同一类型)但是(不装饰 Person class)我将如何获得属性 Id 类型 PersonIdentity 在我的 Person class 上使用此序列化程序进行序列化?

所以,方法是注册一个serialization provider。这将让您拦截所有解析身份的尝试,并用它们做任何您想做的事。