Want to replace wcf serializer with a custom one.
After googling I’ve found examples. But it do not work.
Here is my code:
Substitutor:
internal class MySerializerSubstitutor : DataContractSerializerOperationBehavior
{
private static readonly MySerializer _serializer = new MySerializer();
public MySerializerSubstitutor (OperationDescription operationDescription)
: base(operationDescription)
{
}
public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)
{
return _serializer; //NEVER CALLED
}
public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
{
return _serializer; // NEVER CALLED
}
}
Behavior which repolace serializer
public class MySerializerBehavior : IOperationBehavior
{
…….
public void ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch)
{
var dcs = description.Behaviors.Find<DataContractSerializerOperationBehavior>();
if (dcs != null)
description.Behaviors.Remove(dcs);
description.Behaviors.Add(new MySerializerSubstitutor(description)); //works fine
}
………….
}
And host:
protected override void ApplyConfiguration()
{
var behavior = new MySerializerBehavior()
foreach (var op in Description.Endpoints.SelectMany(ep => ep.Contract.Operations))
{
op.Behaviors.Add(behavior);
}
}
Whats wrong with this code?
One problem that is immediately visible is that you cannot replace a behavior from a behavior. According to MSDN:
http://msdn.microsoft.com/en-us/library/system.servicemodel.description.ioperationbehavior.aspx
I am not 100% sure what you are trying to accomplish, but here is an example that modifies properties of the serializer behavior.
http://msdn.microsoft.com/en-us/library/system.servicemodel.description.datacontractserializeroperationbehavior.aspx
If you need more customization than the properties provide you can try to replace the DataContractSerializerOperationBehavior. EDIT: Just make sure you add it before calling Open. See this article for adding a new behavior http://msdn.microsoft.com/en-us/library/ms730137.aspx