Using relative URLs to access WCF services in Silverlight

If you are developing a silverlight application with a WCF service, chances are that you will encounter a Service Not Found error due to any of the following reasons:

  • The VS Development Server port changed
  • You deployed your application on IIS for testing.
  • You deployed your application on any other computer.

Now there are two apparent choices:

  • Modify the URL in ServiceReferences.ClientConfig file
  • Use “relative” URLs instead of directly instantiating the service client.

The first solution is to modify ServiceReferences.ClientConfig file and correct the URL of the service. However, this is difficult once the application is deployed since the config file is contained inside the .xap file. I will present the second solution here.

Replace you service client instantiation (the following code):

 MyServiceClient svc=new MyServiceClient();

with a method call GetMyServiceClient() as:

 MyServiceClient svc = GetMyServiceClient();

And define GetMyServiceClient() as:

private MyServiceClient GetMyServiceClient()
{
  Binding binding = new System.ServiceModel.BasicHttpBinding();
  EndpointAddress endpoint = new EndpointAddress(
	new Uri(Application.Current.Host.Source, "../MyService.svc"));
  MyServiceClient service = new MyServiceClient(binding, endpoint);
  return service;
}

The above code dynamically builds the service URL from application path. It is a good practice to have service initialization code in one place and you can also control certain other settings (e.g. max buffer size, timeout settings) for your service in that method.

If you need to use the configurations from ServiceReferences.ClientConfig file and modify just the url, you may use another overload that takes the configuration name as parameter:

private MyServiceClient GetMyServiceClient()
{
  EndpointAddress endpoint = new EndpointAddress(
	new Uri(Application.Current.Host.Source, "../MyService.svc"));
  MyServiceClient service = new MyServiceClient("CustomBinding_MyService", endpoint);
  return service;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: