Creating a Silverlight WCF Binary Encoding Client in Code
In Silverlight, it can sometimes bet better to skip using the ServiceReferences.ClientConfig file and instead create your WCF clients from code, specifying the endpoint address. This was pretty simple in Silverlight 2 where all we had was basicHttpBinding. Silverlight 3, however, adds in the ability to use binary message encoding via the binaryMessageEncoding element in the server-side WCF config file – something that is on by default in the Silverlight Enabled WCF Service template.
Assuming you have a generated client (from a service reference) named “ExampleServiceClient”, here’s what the code looks like. The key entry is the BinaryMessageEncodingBindingElement. This may be obvious to folks who do tons of custom WCF work :)
private ExampleServiceClient BuildExampleServiceClient()
{
BindingElementCollection elements = new BindingElementCollection();
// order of entries in collection is significant: dumb.
elements.Add(new BinaryMessageEncodingBindingElement());
elements.Add(new HttpTransportBindingElement());
CustomBinding binding = new CustomBinding(elements);
// insert your favorite address resolution algorithm here
EndpointAddress address = new EndpointAddress(
new Uri("http://localhost:13519/Services/ExampleService.svc", UriKind.Absolute));
ExampleServiceClient client = new ExampleServiceClient(binding, address);
return client;
}
Thanks to Mike Taulty for pointing me in the right direction. I hope that saves you some trouble.