Marc Mora
Marc Mora

Reputation: 49

Protobuf-net not serializing generic type inherits from generic type

I've this model:

[ProtoContract]
[ProtoInclude(2, typeof(TestRequest<>))]
public class XClass<T>
{
    public XClass()
    {
    }

    [ProtoMember(1)]
    public T Value { get; set; }
}

[ProtoContract]
public class TestRequest<T>: XClass<T> where T : ConcreteClass
{

    public TestRequest()
    {
    }

}

[ProtoContract]
public class ConcreteClass
{
    [ProtoMember(1)]
    public string Name { get; set; }
}

And if I try to serialize and deserialize with protobuf-net :

TestRequest<ConcreteClass> request = new TestRequest<ConcreteClass>();
request.Value = new ConcreteClass() { Name = "test" };
MemoryStream msTestString = new MemoryStream();
Serializer.Serialize(msTestString, request);
msTestString.Position = 0;
request = Serializer.Deserialize < TestRequest<ConcreteClass>>(msTestString);

And after this, If I inspect request.Value , it's null.

What I'm doing wrong?

Upvotes: 4

Views: 1329

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1064314

From protobuf-net's perspective, it is primed and ready to receive the open generic type TestRequest<> as field 2... however, nothing ever exists as TestRequest<>: only closed generic types exist as actual objects, so TestRequest<> is simply not useful to protobuf-net.

What would work in some scenarios is:

[ProtoContract]
[ProtoInclude(2, typeof(TestRequest<Foo>))]
[ProtoInclude(3, typeof(TestRequest<Bar>))]
[ProtoInclude(4, typeof(TestRequest<Blap>))]

However, it probably isn't a good idea to mix this with generics themselves.

I suspect what you actually want is:

[ProtoContract]
[ProtoInclude(2, typeof(TestRequest<T>))]
public class XClass<T> {}

however, I have no idea if that even compiles, let alone if it is what you are after. In reality, my opinion is that if you're getting tied into this kind of knot, you're probably over-complicating your serialization model - often the result of trying to serialize you primary domain model - and maybe it is time to move to a simpler, dedicated model.

Upvotes: 1

Immortal Blue
Immortal Blue

Reputation: 1700

This is by design with protobuf-net. One of the reasons it is so quick and light on data is that it doesn't worry about type information. This, unfortunately (Well, depending on your point of view) completely rules out inheritance with it.

see protobuf with inheritance? for more info

Upvotes: 1

Related Questions