Snippet: Construct WCF Binding from string (xml)

Here is a snippet to convert a bindingconfiguration xml fragment into a Binding (with a few limitations).

Configuration configSystem = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var bindingSection = BindingsSection.GetSection(configSystem);
string customConfig = “<netTcpBinding><binding name=\”netTcpBinding\” maxReceivedMessageSize=\”12345\” hostNameComparisonMode=\”Exact\” /></netTcpBinding>”;
// another example: 
// string customConfig = “<binding name=\”basicHttpBinding\” messageEncoding=\”Mtom\” maxReceivedMessageSize=\”14000\” allowCookies=\”True\” /></basicHttpBinding>”;
bindingSection.SectionInformation.SetRawXml(string.Format (“<bindings>{0}</bindings>”,customConfig));
BindingCollectionElement bindingCollectionElement = null;
foreach (BindingCollectionElement bicoelem in bindingSection.BindingCollections)
    if (0 < bicoelem.ConfiguredBindings.Count)
        bindingCollectionElement = bicoelem;
var newBinding = (Binding)bindingCollectionElement.BindingType.Assembly.CreateInstance(bindingCollectionElement.BindingType.FullName);
IBindingConfigurationElement bEleEx = bindingCollectionElement.ConfiguredBindings[0];

At this point the newBinding is configured with the configurationoptions you added in the “customConfig” string.


Comments (1)

  1. dist says:

    Thank you for this!

    Do you have a list of the "few limitations" of this method?

    It seems that the binding name is not reflected on newBinding and a default one is used, any idea?

    Finally on MSDN : "This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", any comments on this?

Skip to main content