WCF中的StackOverflowException与DataContractSerializer和IsReference = true

时间:2011-10-14 14:21:12

标签: wcf stack-overflow

我们正在使用EF4 POCO& amp; WCF 4.0。我们正在使用DataContractSerializer,我们添加了IsReference=true

延迟加载已停用且应用程序正常运行但现在在其中一个实体的某些实例上,我们看到StackOverflowException。我们之前有过循环引用,没有问题。

有关如何进行的任何提示?

1 个答案:

答案 0 :(得分:0)

用于测试与DataContract属性相关的问题的代码:

public class ObjectGraphValidator
{
    List<object> _knownObjects = new List<object>();
    Dictionary<Type, int> _encounteredCount = new Dictionary<Type, int>();
    List<Type> _nonReferenceTypes = new List<Type>();

    public void ValidateObjectGraph(object obj)
    {
        Type type = obj.GetType();
        if (_encounteredCount.ContainsKey(type))
            _encounteredCount[type]++;
        else
        {
            _encounteredCount.Add(type, 1);
            if (type.IsValueType)
                _nonReferenceTypes.Add(type);
            DataContractAttribute att = Attribute.GetCustomAttribute(type, typeof(DataContractAttribute)) as DataContractAttribute;
            if (att == null || !att.IsReference)
                _nonReferenceTypes.Add(type);
        }

        if (obj.GetType().IsValueType)
            return;
        if (_knownObjects.Contains(obj))
            return;
        _knownObjects.Add(obj);
        if (obj is IEnumerable)
            foreach (object obj2 in (obj as IEnumerable))
                ValidateObjectGraph(obj2);
        foreach (PropertyInfo property in type.GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
            if (property.GetIndexParameters().Count() == 0)
            {
                object value = property.GetValue(obj, null);
                if (value == null)
                    continue;
                ValidateObjectGraph(value);
            }
    }
}