Calling services from Silverlight 2 part 2| Comments
- | Posted in
- web service
- cross domain
In a previous post, I wrote about some samples of calling various types of services from Silverlight 2. In the code, I was using constructors in my ASMX and WCF services with specifying a binding type and endpoint address.
It was called out to me that in other demonstrations, people did not use this construct. While the method I demonstrated works (explicitly specifying the binding and endpoint), in some cases it may not be necessary. One such case would be if you only have one endpoint and it is basicHttpBinding.
The error in my code/instructions was about changing the binding information in web.config. The information is correct, however I wasn't clear on when/what you needed to do. For example, the default information in web.config for the Silverlight project created for you uses wsHttpBinding. If you add a service reference in your Silverlight project PRIOR to changing that binding information, your generated proxy will require you to specify a binding and endpoint as Silverlight doesn't support wsHttpBinding and it would be trying to use that as a default method.
So the appropriate way is to change the binding type in your web.config FIRST. Then generate the service reference in your Silverlight application and your proxy code generated will then allow you to new up the service using:
WcfServiceClient wcf = new WcfServiceClient();
for both WCF and ASMX services...which is probably more familiar to most web developers implementing services in their applications.
Again, EITHER way is fine. Providing no information in the constructor will use the default binding/endpoint information for that service, and if it isn't supported, you'll get a nasty exception. Whether or not it is best practice to always explicitly call it out in your code is up to you. I'd argue it is. In looking at the code above do you know what binding/endpoint is being used at the time of the service call? No. You could make some reasonable assumptions (hey, I'm in Silverlight and I know I must use basicHttpBinding), but for maintainability, maybe someone else coming to the code doesn't have the same understanding.
To each his own. Either way, I hope this clarifies and I've updated my post with the note about this as well.
Please enjoy some of these other recent posts...