Silverlight Deployment and WCF Endpoints

I'm sure this has been written about a ton, but why not repost some useful information.

When using Silverlight with WCF, you quickly learn about the cross-domain restrictions. It becomes a huge pain when deploying from dev to production because you have to deploy and configure your Silverlight using the prod endpoint address, which for me at least didn't always work. So what I found was that quite a few people are setting their WCF client end points on the fly using the current host during runtime. It's relatively easy to do, and since they both are typically deployed at the same time, it works out pretty well.

This snippet strips away the ClientBin/xxx.xap from the application source and retains the application root URL.

string full = Application.Current.Host.Source.AbsoluteUri;  
full = full.Substring(0, full.LastIndexOf('/')) + "/../";

You can then put this functionality into a utility class for your application and make it very easy to consume when using WCF services. Using the music manager service from a previous post, we have:

MusicManagerService.MusicManagerServiceClient client;  
client = new MusicPlayer.MusicManagerService.MusicManagerServiceClient();

//use dynamic endpoint
client.Endpoint.Address = new System.ServiceModel.EndpointAddress(full + "MusicManager.svc"); 

client.GetFilesCompleted +=new EventHandler<MusicPlayer.MusicManagerService.GetFilesCompletedEventArgs>(client_GetFilesCompleted);  
client.GetFilesAsync(uxSearchString.Text.Trim());

For deployment, you just xcopy your published web app to the deployment directory and you're done. No reconfiguring/recompiling necessary.

Enjoy!