BindingManager- How to read WCF Binding from configuration?

BindingManager reads the binding configured in the web.config and apply them at Endpoint. BindingManager is reading ServiceModel section from web.config but you can change the code to read from exe.config easily. You can load the binding from configuration file and make modification at Runtime before applying to an endpoint.

When a WCF service starts, the build-in ServiceHost will call ApplyConfiguration() method to apply behaviors and binding specified in the ServiceModel section of the config file. You must have your own derived ServiceHost and override the ApplyConfiguration() method, to control the behaviors and binding at Runtime.

I will be writing a separate post on ServiceHost and ServiceHostFactory and you will get to see how to connect the dots. For now, let’s see how you can load binding from configuration by bindingconfiguration name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.Configuration;
using System.Collections;

namespace WCF.Bindings
{
	public class BindingManager
	{
		private static Hashtable bindingHashCollection = new Hashtable();
		private static object lockObject = new object();
 
		public static Binding GetBindingFromConfig(string configurationBindingName)
		{
			Binding binding = null;

			lock (lockObject)
			{
				if (bindingHashCollection.ContainsKey(configurationBindingName))
				{
					binding = (Binding)bindingHashCollection[configurationBindingName];
				}
				else
				{
					var bingingsSection = BindingsSection.GetSection(System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/"));

					IBindingConfigurationElement bindingCollectionElement = null;

					foreach (BindingCollectionElement bindingCollElement in bingingsSection.BindingCollections)
					{
						bool breakOuterLoop = false;

						if (bindingCollElement.ContainsKey(configurationBindingName))
						{
							foreach (IBindingConfigurationElement configuredElement in bindingCollElement.ConfiguredBindings)
							{
								if (configuredElement.Name == configurationBindingName)
								{
									bindingCollectionElement = configuredElement;
									binding = (Binding)System.Activator.CreateInstance(bindingCollElement.BindingType);
									bindingCollectionElement.ApplyConfiguration(binding);

									if (bindingHashCollection.ContainsKey(configurationBindingName)==false)
									{
										bindingHashCollection.Add(configurationBindingName, binding);
									}

									breakOuterLoop = true;
									break;
								}
							}
						}

						if (breakOuterLoop == true)
						{
							break;
						}
					}
				}
			}

			return binding;
		}
	}  
}

Acknowledgement:
http://weblogs.asp.net/cibrax/archive/2010/05/11/getting-wcf-bindings-and-behaviors-from-any-config-source.aspx

Leave a Reply