Problems with preserving object references in WCF
I'm trying to ensure that my object references are preserved when serialized over WCF, but the CreateSerializer
on my overriden DataContractSerializerOperationBehavior
is never called. Can anybody help me out with this.
This is my code:
Custom DataContractSerializerOperationBehavior:
public class ObjectGraphDataContractSerializerBehavior : DataContractSerializerOperationBehavior
{
/// <summary>
/// Initializes a new instance of the <see cref="ObjectGraphDataContractSerializerBehavior"/> class.
/// </summary>
/// <param name="operationDescription">The operation description.</param>
public ObjectGraphDataContractSerializerBehavior(OperationDescription operationDescription)
: base(operationDescription)
{
}
public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)
{
开发者_如何学Goreturn new DataContractSerializer(type, name, ns, knownTypes,
int.MaxValue /*maxItemsInObjectGraph*/,
false/*ignoreExtensionDataObject*/,
true/*preserveObjectReferences*/,
null/*dataContractSurrogate*/);
}
public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
{
return new DataContractSerializer(type, name, ns, knownTypes,
int.MaxValue /*maxItemsInObjectGraph*/,
false/*ignoreExtensionDataObject*/,
true/*preserveObjectReferences*/,
null/*dataContractSurrogate*/);
}
public static void SetDataContractSerializerBehavior(ContractDescription contractDescription)
{
foreach (OperationDescription operation in contractDescription.Operations)
{
operation.Behaviors.Add(new ObjectGraphDataContractSerializerBehavior(operation));
}
}
}
Starting service host:
var serviceHost = new ServiceHost(typeof (Service));
serviceHost.AddServiceEndpoint(typeof (IService), new NetTcpBinding(), DummyUrl);
foreach (var endpoint in serviceHost.Description.Endpoints)
ObjectGraphDataContractSerializerBehavior.SetDataContractSerializerBehavior(endpoint.Contract);
serviceHost.Open();
Creating channel:
m_ChannelFactory = new ChannelFactory<IService>(m_Binding, new EndpointAddress(m_Url));
ObjectGraphDataContractSerializerBehavior.SetDataContractSerializerBehavior(m_ChannelFactory.Endpoint.Contract);
foreach (var behavior in endpointBehaviors)
m_ChannelFactory.Endpoint.Behaviors.Add(behavior);
It maybe has to do with the selection of which serializer is used. Remove all other serializers and add yours:
public static void SetDataContractSerializerBehavior(ContractDescription contractDescription)
{
foreach (OperationDescription operation in contractDescription.Operations)
{
DataContractSerializerOperationBehavior dcsob = operation.Behaviors.Find<DataContractSerializerOperationBehavior>();
if (dcsob != null)
{
operation.Behaviors.Remove(dcsob);
}
operation.Behaviors.Add(new ReferencePreservingDataContractSerializerOperationBehavior(operation));
}
}
精彩评论