Partilhar via


Replacing the Serializer, Part 2

Last time on the topic of serialization, we were looking at some issues with commonly replicated sample code for preserving object references. Another bit of serializer sample code that gets linked to frequently is Aaron Skonnard's article on an attribute-based method for replacing DataContractSerializer with NetDataContractSerializer. The issue with this code is much more subtle and harder to correct.

The basic premise of the sample is to build a behavior that gets tagged onto operations via an attribute. That behavior then replaces the standard serializer with NetDataContractSerializer at runtime. Let's look at the piece that actually does the replacement.

 public void ApplyClientBehavior(OperationDescription description, ClientOperation proxy)
{
   ReplaceDataContractSerializerOperationBehavior(description);
}

public void ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch)
{
   ReplaceDataContractSerializerOperationBehavior(description);
}

private static void ReplaceDataContractSerializerOperationBehavior(OperationDescription description)
{
   DataContractSerializerOperationBehavior dcsOperationBehavior = description.Behaviors.Find<DataContractSerializerOperationBehavior>();
   if (dcsOperationBehavior != null)
   {
      description.Behaviors.Remove(dcsOperationBehavior);
      description.Behaviors.Add(new NetDataContractSerializerOperationBehavior(description));
   }
}

When the behavior executes on the client or server, the ReplaceDataContractSerializerOperationBehavior method is run. That method fishes the old serialization behavior out of the description and replaces it with a behavior for NetDataContractSerializer. The issue here is that we are modifying the service description from within ApplyClientBehavior and ApplyDispatchBehavior. Although the service description is still mutable at this time, modifying the description has undefined behavior. This is called out in the documentation for using behaviors. Other bits of service description code may have already run that have no way to be fixed up when the behavior is swapped out.

Next time: Replacing the Serializer, Part 3

Comments