是否有"后反序列化钩子"?

时间:2015-01-20 16:24:33

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

使用mongo C#驱动程序,我可以进入反序列化过程,这样对于Foo类型的每个反序列化对象,我可以在它返回给调用者之前立即操作该对象吗?

简化示例:

class Foo
{
    [BsonIgnore]
    public bool IsChanged {get;set;}

    ...
}

...

var foo = Collection.FindOneByIdAs<Foo>(id);
foo.IsChanged; // true

2 个答案:

答案 0 :(得分:2)

是的,您可以从.NET框架实现ISupportInitialize,我们将适当地调用它。请参阅我们的文档:http://docs.mongodb.org/ecosystem/tutorial/serialize-documents-with-the-csharp-driver/#implementing-isupportinitialize

答案 1 :(得分:1)

是的,您可以使用自定义Foo Serializer

public class FooSerialzer : BsonBaseSerializer
{
    private static readonly IBsonSerializer Serializer;

    static FooSerialzer()
    {
        var classMap = BsonClassMap.LookupClassMap(typeof(Foo));
        var serializerType = Type.GetType("MongoDB.Bson.Serialization.BsonClassMapSerializer, MongoDB.Bson", true);
        Serializer = (IBsonSerializer)Activator.CreateInstance(serializerType, classMap);
    }

    public override object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
    {
        var document = BsonSerializer.Deserialize<BsonDocument>(bsonReader);
        var foo = (Foo)Serializer.Deserialize(BsonReader.Create(document), typeof(Foo), options);

        // do your customization for foo here
        return foo;
    }

    public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
    {
        var foo = (Foo) value;
        foo.Id = ObjectId.GenerateNewId().ToString();

        var document = new BsonDocument();
        Serializer.Serialize(BsonWriter.Create(document), nominalType, value, options);

        BsonSerializer.Serialize(bsonWriter, document);
    }
}

请记住在您的应用启动中注册此内容

BsonSerializer.RegisterSerializer(typeof(Foo), new FooSerialzer());

在这种情况下,您不必为复杂对象序列化和反序列化。