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.
bindingConfiguration : A string that specifies the binding name of the binding to use when the endpoint is instantiated. The binding name must be in scope at the point the endpoint is defined. The default is an empty string.
To do this, you add the individual binding elements to a collection represented by an instance of the BindingElementCollection class, and then set the Elements property of the CustomBinding equal to that object.
BasicHttpBinding is suitable for communicating with ASP.NET Web Service (ASMX) based services that conform to the WS-Basic Profile that conforms with Web Services. This binding uses HTTP as the transport and text/XML as the default message encoding. Security is disabled by default.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With