I would like to get Binding object from web.config or app.config.
So, this code works:
wcfTestClient = new TestServiceClient("my_endpoint", Url + "/TestService.svc");
but I would like to do the following:
Binding binding = DoSomething();
wcfTestClient = new TestServiceClient(binding, Url + "/TestService.svc");
I am interested in DoSomething() method, of course.
This answer fulfills the OP request and is 100% extracted from this amazing post from Pablo M. Cibraro.
http://weblogs.asp.net/cibrax/getting-wcf-bindings-and-behaviors-from-any-config-source
This method gives you the config's binding section.
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;
}
This method gives you the actual Binding
object you are so desperately needing.
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;
}