Search code examples
c#wcfentity-frameworkdatacontractserializer

WCF Circular Reference Serialization & Stack Overflow Error


I have the following problem, given the following service contract, data contract, and service implementation, how should I get WCF to serialize my object graph without stack overflowing?

Service Contract:

[ServiceContract]
public interface IService1
{
    [OperationContract]
    TestObjectA CircularSerializationTest();
}

Data Contracts

[DataContract(IsReference = true)]
public class TestObjectA
{
    [DataMember]
    public TestObjectB B { get; set; }
}

[DataContract(IsReference = true)]
public class TestObjectB
{
    [DataMember]
    public TestObjectC C { get; set; }
}

[DataContract(IsReference = true)]
public class TestObjectC
{
    [DataMember]
    public TestObjectA A { get; set; }
}

Service Implementation:

public class Service1 : IService1
{
    public TestObjectA CircularSerializationTest()
    {
        var a = new TestObjectA();
        var b = new TestObjectB();
        var c = new TestObjectC();

        a.B = b;
        b.C = c;
        c.A = a;

        return a;
    }
}

Why is this question unique? First, every other example I've been able to find uses a tree of objects, or it uses circular references between two objects. In the instance of a tree (Grandparent => Parent => Child) the relationship isn't actually circular, but objects are used between different nodes. Or, in the second case, either the same object is circular (Person has a list of employees that are also persons, this is in one of the example I found on the MSDN) or its a parent => child => parent relationship which is circular, but not quite extensive enough.

Also, in my case, its not possible to 'flatten' the objects into a tree, they need to maintain the same object references.

Thanks in advance to any advice or insight into this problem.


Solution

  • I figured it out.

    It seems the stack overflow isn’t actually occurring in WCF at all, it’s actually happening in the WCF test client. I think Visual Studio must connect to it because when it crashes, it blows up inside of visual studio which is why I thought it was a problem with the service. The test client displays the result as a tree, and my guess is that they didn’t anticipate that the result could be a cyclic object graph, thus the stack overflow.

    Lesson Learned: Don’t use the WCF test client. Use a console app.