Darbio
Darbio

Reputation: 11418

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

Is there a way to set a custom serializer for all types which inherit from a specific base type?

Given the following types:

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

With the following model:

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

And the following serializer:

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

I figured that BsonSerializer.RegisterSerializer(typeof(StringIdentity), new StringIdentitySerializer()); would serialize my property Id on Person as a string.

This serializer works when I change the Id property to be of type StringIdentity.

I understand why this is happening (PersonIdentity is not the same type as StringIdentity) but (without decorating the Person class) how would I get the property Id of type PersonIdentity on my Person class to serialize using this serializer?

Upvotes: 3

Views: 6215

Answers (1)

Craig Wilson
Craig Wilson

Reputation: 12624

So, the way to do this is to register a serialization provider. This will let you intercept all attempts to resolve an Identity and do whatever it is you want to do with them.

Upvotes: 2

Related Questions