日期:2014-05-20 浏览次数:20895 次
public static Binding GetBinding(string bindingTypeName, string bindingName)
        {
            IBindingConfigurationElement element = GetBindingConfiguration(bindingTypeName, bindingName);
            return GetBinding(element);
        }
private static Binding GetBinding(IBindingConfigurationElement configurationElement)
        {
            Binding b = null;
            if (configurationElement is CustomBindingElement)
                b = new CustomBinding();
            else if (configurationElement is BasicHttpBindingElement)
                b = new BasicHttpBinding();
            else if (configurationElement is NetMsmqBindingElement)
                b = new NetMsmqBinding();
            else if (configurationElement is NetNamedPipeBindingElement)
                b = new NetNamedPipeBinding();
            else if (configurationElement is NetPeerTcpBindingElement)
                b = new NetPeerTcpBinding();
            else if (configurationElement is NetTcpBindingElement)
                b = new NetTcpBinding();
            else if (configurationElement is WSDualHttpBindingElement)
                b = new WSDualHttpBinding();
            else if (configurationElement is WSHttpBindingElement)
                b = new WSHttpBinding();
            else if (configurationElement is WSFederationHttpBindingElement)
                b = new WSFederationHttpBinding();
            else
                throw new NotSupportedException();
            configurationElement.ApplyConfiguration(b);
            return b;
        }
private static IBindingConfigurationElement GetBindingConfiguration(string bindingTypeName, string bindingName)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(YOUR CONFIGURATION FILE PATH);
            var c = config.GetSectionGroup("system.serviceModel") as ServiceModelSectionGroup;
            BindingCollectionElement element = c.Bindings.BindingCollections.FirstOrDefault(bc =>
            {
                return string.Equals(bc.BindingName, bindingTypeName, StringComparison.OrdinalIgnoreCase);
            });
            if (element == null)
            {
                throw new NotSupportedException();
            }
            return element.ConfiguredBindings.FirstOrDefault(b =>
            {
                return string.Equals(b.Name, bindingName, StringComparison.OrdinalIgnoreCase);
            });
        }