这个答案满足了 OP 的要求,并且 100% 来自 Pablo M. Cibraro 的这篇精彩的帖子。
http://weblogs.asp.net/cibrax/getting-wcf-bindings-and-behaviors-from-any-config-source
此方法为您提供配置的绑定部分。
private BindingsSection GetBindingsSection(string path)
{
System.Configuration.Configuration config =
System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(
new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = path },
System.Configuration.ConfigurationUserLevel.None);
var serviceModel = ServiceModelSectionGroup.GetSectionGroup(config);
return serviceModel.Bindings;
}
此方法为您提供了您Binding
迫切需要的实际对象。
public Binding ResolveBinding(string name)
{
BindingsSection section = GetBindingsSection(path);
foreach (var bindingCollection in section.BindingCollections)
{
if (bindingCollection.ConfiguredBindings.Count > 0
&& bindingCollection.ConfiguredBindings[0].Name == name)
{
var bindingElement = bindingCollection.ConfiguredBindings[0];
var binding = (Binding)Activator.CreateInstance(bindingCollection.BindingType);
binding.Name = bindingElement.Name;
bindingElement.ApplyConfiguration(binding);
return binding;
}
}
return null;
}