我正在尝试确保在通过WCF序列化时保留我的对象引用,但是我的覆盖CreateSerializer
上的DataContractSerializerOperationBehavior
永远不会被调用。任何人都可以帮我解决这个问题。
这是我的代码:
自定义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)
{
return 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));
}
}
}
启动服务主机:
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();
创建频道:
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);
答案 0 :(得分:1)
这可能与选择使用哪种串行器有关。删除所有其他序列化程序并添加您的序列号:
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));
}
}