Share via


WCF Extensibility – IContractBehavior

This post is part of a series about WCF extensibility points. For a list of all previous posts and planned future ones, go to the index page.

Going down the list of behaviors, the second one to be covered is the IContractBehavior. Like the other ones, it can be used to inspect or change the contract description and its runtime for all endpoints which have that contract. For example, the behavior can validate the contract against the binding to ensure that the it’s used the contract is only used with appropriate, or it can modify the runtime for all its operations in a centralized location. Unlike IServiceBehavior mentioned in the previous post, the IContractBehavior is also used to change the client runtime.

Public implementations in WCF

  • DeliveryRequirementsAttribute: Defines ordering requirements for the binding which uses the contract, such as whether the contract requires ordered or queued delivery.
  • ServiceMetadataContractBehavior (new in 4.0): Determines whether endpoints with the given contract should be exposed in the service metadata.
  • JavascriptCallbackBehaviorAttribute: For REST/JSON endpoints, defines the URL query string parameter name which needs to be passed to change the response from “normal” JSON to JSONP.

 

Interface declaration

  1. public interface IContractBehavior
  2. {
  3.     void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint);
  4.     void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime);
  5.     void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime);
  6.     void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters);
  7. }

As was mentioned in the post about Behaviors, you can use the Validate method to ensure that the contract doesn’t violate the validation logic on the behavior. One example is the DeliveryRequirementsAttribute, which throws if the behavior requires ordered message delivery but it’s not there (i.e., using HTTP, MSMQ), or if the behavior says that it cannot have queued delivery but the binding provides that.

AddBindingParameters is used to pass information to the binding elements themselves. It’s not used as often, but one (not too common) example would be for a contract, after validating that the binding does not contain any message encoding binding elements, to add one in the binding parameters at this method, thus guaranteeing that it would always use that encoding type.

ApplyDispatchBehavior is the method which is most used in the server side. It’s called right after the runtime was initialized, so at that point the code has access to the listeners / dispatchers / runtime objects for the server, and can add / remove / modify those. The example below will use an endpoint behavior to change the serializer used by all of the operations in the contract.

ApplyClientBehavior is the counterpart to ApplyDispatchBehavior for the client side. After the client runtime is initialized, the method is called so that the code can update the client runtime objects.

How to add a contract behavior

Via the service / endpoint description (server) : On the server side, once you add an endpoint you can get a reference to it, then you can access its Contract property, and from there you can access the behavior collection.

  1. string baseAddress = "https://" + Environment.MachineName + ":8000/Service";
  2. ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
  3. ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), "");
  4. endpoint.Contract.Behaviors.Add(new MyContractBehavior());

Via the channel factory / generated proxy (client) : The ChannelFactory class has an Endpoint property which is of the same type as the one on the server. Likewise, generated proxies (using svcutil / add service reference) are subclasses of ClientBase<T>, which also has an Endpoint property which contains a reference to the contract description, and from there to the behavior collection. Just remember that, once the endpoint has been opened (for channel factories, when it’s been explicitly opened or a channel created; for generated clients when it’s been explicitly opened or an operation called), modifying the description will have no effect on the runtime, since it’s already been created).

  1. ChannelFactory<ITest> factory = new ChannelFactory<ITest>(binding, new EndpointAddress(address));
  2. factory.Endpoint.Contract.Behaviors.Add(new MyContractBehavior());
  3. ITest proxy = factory.CreateChannel();

Using attributes: if the contract behavior is derived from System.Attribute, it can be applied to either the contract interface or the service class, and it will be added to the contract description by WCF. If it’s applied to the contract interface, it will be added to the contract description in all endpoints which use that contract (both server and client). If the attribute is applied to the service implementation, it will be applied to all contracts implemented by the service (unless the attribute also implements the IContractBehaviorAttribute interface, in which case it can be restricted to a single contract type – see more information in the remarks section of the documentation for IContractBehavior.

  1. public class MyContractBehaviorAttribute : Attribute, IContractBehavior
  2. {
  3.     // IContractBehavior implementation
  4. }
  5. [ServiceContract]
  6. [MyContractBehavior]
  7. public interface ICalculator
  8. {
  9.     [OperationContract]
  10.     int Add(int x, int y);
  11. }

Using configuration: Configuration is not an option for adding endpoint behaviors.

Real world scenario: using a new serializer

This has come up a few times in the forums (1, 2, 3, …). Most of the time it’s about forcing WCF to use XmlSerializer, or replace the default DataContractSerializer with the NetDataContractSerializer (to avoid having to deal with known types in inheritance-heavy scenarios). Other times people really need a new way of serializing / deserializing objects – for performance or size reasons, for example. In this example I have a custom serializer which knows how to serialize very compactly some data types which are tagged with a specific interface. The interface is a simple one with two methods: one for the object to serialize itself into a stream, and another for an object to initialize itself from a stream.

  1. public interface ICustomSerializable
  2. {
  3.     void WriteTo(Stream stream);
  4.     void InitializeFrom(Stream stream);
  5. }

And before I go any further, here goes the usual disclaimer – this is a sample for illustrating the topic of this post, this is not production-ready code. I tested it for a few inputs and it worked, but I cannot guarantee that it will work for all types (please let me know if you find a bug or something missing). Also, for simplicity sake it doesn’t have a lot of error handling which a production-level code would. Finally, this sample (as well as most other samples in this series) uses extensibility points other than the one for this post (e.g., operation behavior, custom serializers, etc.) which are necessary to get a realistic scenario going. I’ll briefly describe what they do, and leave to their specific entries a more detailed description of their behavior.

Below are a few types which implement this interface. They use some helper functions to read/write data in a compact binary format (the code for the helper can be found in the [Code for this post] link at the end). This is a format similar to the one used by the .NET XML Binary Format (the one used by the binary encoding in WCF).

  1. public class Product : ICustomSerializable
  2. {
  3.     public string Name;
  4.     public string Unit;
  5.     public int UnitPrice;
  6.  
  7.     public void WriteTo(Stream stream)
  8.     {
  9.         FormatHelper.WriteString(stream, this.Name);
  10.         FormatHelper.WriteString(stream, this.Unit);
  11.         FormatHelper.WriteInt(stream, this.UnitPrice);
  12.     }
  13.  
  14.     public void InitializeFrom(Stream stream)
  15.     {
  16.         this.Name = FormatHelper.ReadString(stream);
  17.         this.Unit = FormatHelper.ReadString(stream);
  18.         this.UnitPrice = FormatHelper.ReadInt(stream);
  19.     }
  20. }
  21.  
  22. public class Order : ICustomSerializable
  23. {
  24.     public int Id;
  25.     public Product[] Items;
  26.     public DateTime Date;
  27.  
  28.     public void WriteTo(Stream stream)
  29.     {
  30.         FormatHelper.WriteInt(stream, this.Id);
  31.         FormatHelper.WriteInt(stream, this.Items.Length);
  32.         for (int i = 0; i < this.Items.Length; i++)
  33.         {
  34.             this.Items[i].WriteTo(stream);
  35.         }
  36.  
  37.         FormatHelper.WriteLong(stream, this.Date.ToBinary());
  38.     }
  39.  
  40.     public void InitializeFrom(Stream stream)
  41.     {
  42.         this.Id = FormatHelper.ReadInt(stream);
  43.         int itemCount = FormatHelper.ReadInt(stream);
  44.         this.Items = new Product[itemCount];
  45.         for (int i = 0; i < itemCount; i++)
  46.         {
  47.             this.Items[i] = new Product();
  48.             this.Items[i].InitializeFrom(stream);
  49.         }
  50.  
  51.         this.Date = DateTime.FromBinary(FormatHelper.ReadLong(stream));
  52.     }
  53. }

Now to the behavior. In order to easily share the behavior between client and server (after all, both sides need to agree on the serialization format), I’m implementing it as an attribute, so we can share the contract definition between the parties and it will be decorated with the behavior. The behavior will do two things: validate that all types which will use the new serializer can be created (i.e., they’re public types with a public, parameter-less constructor), and replace a behavior in all of the contract operations. The behavior which selects the serializer in WCF is the DataContractSerializerOperationBehavior (DCSOB), whose task is to add a formatter to the runtime which knows how to convert between the incoming / outgoing message and the parameters in the operations. We could create a new formatter to do that, but inheriting from DCSOB (even though we won’t be using the DataContractSerializer for our custom serialization) will save us time, as it exposes two helper virtual methods that makes it easier to replace the serializer).

  1. public class MyNewSerializerContractBehaviorAttribute : Attribute, IContractBehavior
  2. {
  3.     public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
  4.     {
  5.     }
  6.  
  7.     public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
  8.     {
  9.         this.ReplaceSerializerOperationBehavior(contractDescription);
  10.     }
  11.  
  12.     public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
  13.     {
  14.         this.ReplaceSerializerOperationBehavior(contractDescription);
  15.     }
  16.  
  17.     public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
  18.     {
  19.         foreach (OperationDescription operation in contractDescription.Operations)
  20.         {
  21.             foreach (MessageDescription message in operation.Messages)
  22.             {
  23.                 this.ValidateMessagePartDescription(message.Body.ReturnValue);
  24.                 foreach (MessagePartDescription part in message.Body.Parts)
  25.                 {
  26.                     this.ValidateMessagePartDescription(part);
  27.                 }
  28.  
  29.                 foreach (MessageHeaderDescription header in message.Headers)
  30.                 {
  31.                     this.ValidateCustomSerializableType(header.Type);
  32.                 }
  33.             }
  34.         }
  35.     }
  36.  
  37.     private void ValidateMessagePartDescription(MessagePartDescription part)
  38.     {
  39.         if (part != null)
  40.         {
  41.             this.ValidateCustomSerializableType(part.Type);
  42.         }
  43.     }
  44.  
  45.     private void ValidateCustomSerializableType(Type type)
  46.     {
  47.         if (typeof(ICustomSerializable).IsAssignableFrom(type))
  48.         {
  49.             if (!type.IsPublic)
  50.             {
  51.                 throw new InvalidOperationException("Custom serialization is supported in public types only");
  52.             }
  53.  
  54.             ConstructorInfo defaultConstructor = type.GetConstructor(new Type[0]);
  55.             if (defaultConstructor == null)
  56.             {
  57.                 throw new InvalidOperationException("Custom serializable types must have a public, parameterless constructor");
  58.             }
  59.         }
  60.     }
  61.  
  62.     private void ReplaceSerializerOperationBehavior(ContractDescription contract)
  63.     {
  64.         foreach (OperationDescription od in contract.Operations)
  65.         {
  66.             for (int i = 0; i < od.Behaviors.Count; i++)
  67.             {
  68.                 DataContractSerializerOperationBehavior dcsob = od.Behaviors[i] as DataContractSerializerOperationBehavior;
  69.                 if (dcsob != null)
  70.                 {
  71.                     od.Behaviors[i] = new MyNewSerializerOperationBehavior(od);
  72.                 }
  73.             }
  74.         }
  75.     }
  76.  
  77.     class MyNewSerializerOperationBehavior : DataContractSerializerOperationBehavior
  78.     {
  79.         public MyNewSerializerOperationBehavior(OperationDescription operation) : base(operation) { }
  80.         public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)
  81.         {
  82.             return new MyNewSerializer(type, base.CreateSerializer(type, name, ns, knownTypes));
  83.         }
  84.  
  85.         public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
  86.         {
  87.             return new MyNewSerializer(type, base.CreateSerializer(type, name, ns, knownTypes));
  88.         }
  89.     }
  90. }

Finally, the serializer. Implementing a new WCF serializer is a matter of finding a mapping between XML (the internal format used by WCF messages) and the format you want. For this optimized serialization, I’ll use a very simple mapping which writes the serialized object as binary data, wrapped inside a XML element. The mapping is done by subclassing XmlObjectSerializer, by overriding a few methods about reading / writing the object from / to XML reader / writers. Also, since there are types which can be used in the operation but aren’t ready for optimized serialization, the serializer is holding on to a reference to the original serializer from WCF, so that they can be used as well. So the implementation checks whether the type being serialized supports custom serialization; if it does, the new logic is used; otherwise it delegates the call to the original serializer for that type.

  1. public class MyNewSerializer : XmlObjectSerializer
  2. {
  3.     const string MyPrefix = "new";
  4.     Type type;
  5.     bool isCustomSerialization;
  6.     XmlObjectSerializer fallbackSerializer;
  7.     public MyNewSerializer(Type type, XmlObjectSerializer fallbackSerializer)
  8.     {
  9.         this.type = type;
  10.         this.isCustomSerialization = typeof(ICustomSerializable).IsAssignableFrom(type);
  11.         this.fallbackSerializer = fallbackSerializer;
  12.     }
  13.  
  14.     public override bool IsStartObject(XmlDictionaryReader reader)
  15.     {
  16.         if (this.isCustomSerialization)
  17.         {
  18.             return reader.LocalName == MyPrefix;
  19.         }
  20.         else
  21.         {
  22.             return this.fallbackSerializer.IsStartObject(reader);
  23.         }
  24.     }
  25.  
  26.     public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
  27.     {
  28.         if (this.isCustomSerialization)
  29.         {
  30.             object result = Activator.CreateInstance(this.type);
  31.             MemoryStream ms = new MemoryStream(reader.ReadElementContentAsBase64());
  32.             ((ICustomSerializable)result).InitializeFrom(ms);
  33.             return result;
  34.         }
  35.         else
  36.         {
  37.             return this.fallbackSerializer.ReadObject(reader, verifyObjectName);
  38.         }
  39.     }
  40.  
  41.     public override void WriteEndObject(XmlDictionaryWriter writer)
  42.     {
  43.         if (this.isCustomSerialization)
  44.         {
  45.             writer.WriteEndElement();
  46.         }
  47.         else
  48.         {
  49.             this.fallbackSerializer.WriteEndObject(writer);
  50.         }
  51.     }
  52.  
  53.     public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
  54.     {
  55.         if (this.isCustomSerialization)
  56.         {
  57.             MemoryStream ms = new MemoryStream();
  58.             ((ICustomSerializable)graph).WriteTo(ms);
  59.             byte[] bytes = ms.ToArray();
  60.             writer.WriteBase64(bytes, 0, bytes.Length);
  61.         }
  62.         else
  63.         {
  64.             this.fallbackSerializer.WriteObjectContent(writer, graph);
  65.         }
  66.     }
  67.  
  68.     public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
  69.     {
  70.         if (this.isCustomSerialization)
  71.         {
  72.             writer.WriteStartElement(MyPrefix);
  73.         }
  74.         else
  75.         {
  76.             this.fallbackSerializer.WriteStartObject(writer, graph);
  77.         }
  78.     }
  79. }

Coming up

The remaining 2 behavior interfaces.

[Code in this post]

[Back to the index]

Carlos Figueira
https://blogs.msdn.com/carlosfigueira
Twitter: @carlos_figueira https://twitter.com/carlos_figueira

Comments

  • Anonymous
    June 25, 2011
    Hello Carlos, What can be wrong in your code if the CreateSerializer method is not called anyway on the client side? While operation behaviors has been tweaked successfully. P.S. NET 4.0, VS2010 SP1 Thanks in advance.

  • Anonymous
    June 25, 2011
    Ruslan, if you add breakpoints in the behavior's ApplyClientBehavior method, and in the MyNewSerializerOperationBehavior's CreateSerializer methods, are any of them hit?