views:

1219

answers:

4

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.

+1  A: 

One cheeky option might be to create an instance with the default constructor, to use as a template:

Binding defaultBinding;
using(TestServiceClient client = new TestServiceClient()) {
    defaultBinding = client.Endpoint.Binding;
}

Then tuck this away and re-use it. Any help?

Marc Gravell
Better than nothing:) But I would like to get binding object from config file, load it by name.
bh213
+3  A: 

You can instantiate a binding giving a binding configuration name from App.config/Web.config.

http://msdn.microsoft.com/en-us/library/ms575163.aspx

Philippe
Only if you know what kind of binding you are going to use, e.g. WSHttpBinding or NetTcpBiding. You lose the flexibility to change the kind of biding at runtime.
Anthony
+2  A: 

Check out this blog post from Mark Gabarra, it shows how to enumerate the configured bindings

Yossi Dahan
A: 

If you don't know the type of the binding until runtime, you can use the following:

return (Binding)Activator.CreateInstance(bindingType, endpointConfigName);

Where bindingType of the type of the binding and endpointConfigName is the name of specified in the config file.

All the included bindings provide a constructor that takes the endpointConfigurationName as the only parameter so this should work for all of them. I have used it for WsHttpBinding and NetTcpBinding without problems.

Jason Gerard