How to create a custom binding from a StandardBinding?

WCF gives a very rich set of standard bindings that you can use for your endpoints. However we might need to tweak properties that might not be exposed on the standard bindings. You can handcraft the whole binding or you can start with standard binding as a template. Here are some ways. 

  1. Create the BindingElementCollection from the StandardBinding and update properties on it and use the BindingElementCollection to create the CustomBinding. This creates a full clone of binding elements and you can reset values on the elements using Find<BindingElement> on the collection.
  2. Create the CustomBinding directly from the StandardBinding by passing the binding into the CustomBinding constructor. The first approach has an issue where properties like SendTimeout/ReceiveTimeout etc don’t get copied onto the CustomBinding since they are held by the Binding and not its child elements & for this simple reason would recommend the second approach.
 BasicHttpBinding httpBinding = new BasicHttpBinding();
httpBinding.SendTimeout = TimeSpan.FromSeconds(123);                        
Console.WriteLine(httpBinding.ToString());

BindingElementCollection bec = httpBinding.CreateBindingElements();
bec.Find<HttpTransportBindingElement>().KeepAliveEnabled = false;
CustomBinding copy1 = new CustomBinding(bec);
Console.WriteLine("SendTimeout = {0} KeepAliveEnabled = {1}", 
    copy1.SendTimeout, 
    copy1.Elements.Find<HttpTransportBindingElement>.KeepAliveEnabled);

CustomBinding copy2 = new CustomBinding(httpBinding);
copy2.Elements.Find<HttpTransportBindingElement>.KeepAliveEnabled = false;
Console.WriteLine("SendTimeout = {0} KeepAliveEnabled = {1}",
    copy2.SendTimeout,
    copy2.Elements.Find<HttpTransportBindingElement>().KeepAliveEnabled);