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.ClientConfigfile - Use “relative” URLs instead of directly instantiating the service client.
The first solution is straight forward, you just need to modify ServiceReferences.ClientConfig file and correct the URL of the service. 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.
