02 March 2011

Silverlight - Dynamic service client and init params

Before, when I connected my Silverlight application to a web service, the web services URI was static. To make this dynamic I referenced System.ServiceModel, and implemented this class:
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Windows;
using EGS.KeyGen.QueryService;

namespace EGS.KeyGen {
  internal class DynamicServiceClient {
    internal static QueryServiceSoapClient GetClient() {
      BasicHttpSecurityMode securityMode = Application.Current.Host.Source.Scheme.Equals("https") ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None;
      BasicHttpBinding binding = new BasicHttpBinding(securityMode);
      binding.MaxReceivedMessageSize = int.MaxValue;
      binding.MaxBufferSize = int.MaxValue;
      return new QueryServiceSoapClient(binding, new EndpointAddress(new Uri(App.ServiceUrl)));
    }
  }
}

When a function wants to retrieve data, it no longer creates a SOAP client itself, but asks one from this class. The dynamic URI is a static property I defined in the App class that takes it's value from the init params on the Silverlight host page:
<param name="initParams" value="ServiceUrl=http://www.EGS.be/QueryService.asmx" />
and sets it like so:
private void Application_Startup(object sender, StartupEventArgs e) {
  if (e.InitParams.ContainsKey("ServiceUrl"))
    ServiceUrl = e.InitParams["ServiceUrl"];
...

And this way I can change the web service end point without having to rebuild the Silverlight application, even though the application still has a static end point from when the service reference was created.

No comments:

Post a Comment