Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF: How to get Binding object from configuration

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.

like image 820
bh213 Avatar asked Dec 10 '08 10:12

bh213


People also ask

What is binding configuration in WCF?

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.

How can custom binding be added to an object that is sealed?

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.

What is BasicHttpBinding?

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.


1 Answers

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;
}
like image 123
daniloquio Avatar answered Oct 11 '22 17:10

daniloquio