Serializing an IEnumerable trough WCF using Protob

2019-04-28 12:59发布

I'm trying to code a WCF service on Monotouch/Monodevelop for IOS. I was using standard attributes like [DataMember]/[DataContract] for my serializable object and [ServiceContract]/[OperationContract] for my interface. Everything worked fine, but when I tried to implement a method returning an IEnumerable on the interface implementation (server side), it didn't worked.

So to solve my problem I tried to use the latest version of protobuf-net being protobuf-net v2 beta r404. But I'm still getting a serialization error from Protobuf-net. Note that the IEnumerable in "MyObject" serialize without problem.

Here's how my code looks right now:

MyObject:

[ProtoContract]
public class MyObject
{
    public MyObject ()
    {
    }

    [ProtoMember(1)]
    public int Id {get;set;}

    [ProtoMember(2)]
    public IEnumerable<MyObject> myObjects {get;set;}
}

My interface (Server side on Windows):

[ServiceContract]
public interface ITouchService
{
        [OperationContract, ProtoBehavior]
        MyObject Execute();

    [OperationContract, ProtoBehavior]
    IEnumerable<MyObject> ExecuteENUM ();
}

My interface (client side on IOS, I can't add ProtoBehavior as attribute becuase it is not in the ISO dll of protobuf):

[ServiceContract]
public interface ITouchService
{
    [OperationContract]
    MyObject Execute();

    [OperationContract]
    IEnumerable<MyObject> ExecuteENUM ();
}

My interface implementation:

public class TouchService : ITouchService
    {
        public MyObject Execute()
        {
            var myObject = new MyObject() { Id = 9001 };

            var myList = new List<MyObject>();

            for (int i = 0; i < 10; i++)
            {
                myList.Add(new MyObject() { Id = i });
            }

// Will serialize
            myObject.myObjects = myList;

            return myObject;

        }

        public IEnumerable<MyObject> ExecuteENUM()
        {
            var myEnum = new List<MyObject>();

            for (int i = 0; i < 10; i++)
            {
                myEnum.Add(new MyObject() { Id = i });
            }

            return myEnum;
        }
    }

1条回答
手持菜刀,她持情操
2楼-- · 2019-04-28 13:23

I suspect it should be possible to tweak the data-contract serializer code for that. I'll take a look.

For now: my advice would be to return an obvious concrete type that has the IEnumerable<T> as a property. Or maybe return a List<T> instead, which might work.

It sounds reasonable to support this scenario, though. I'll see what I can do.

查看更多
登录 后发表回答