Dynamically change WCF Endpoint

23. March 2011 11:33 by Mrojas in General  //  Tags: , , , , , , , , ,   //   Comments (0)

Specially if you are working with Silverlight and Azure you will end up in situation where you would
like to redirect your WCF Endpoint dinamically ( I don’t think you can guess the GUID that Azure will generate
for your staging enviroment).

 

Out of the box the silverlight behaviour is that the WCF endpoints are hardcoded in a config file called
ServicesClient.config embedded in the .xap file.

This can be problematic at least for Azure deployment infraestructure because you can deploy to different sites:
Staging and Production.
Each of this Web Sites will have differente URLs.For example phonebook.cloudapp.net or asdf-asdf-asdf-dasxxx.cloudapp.net

So an easy workaround is:

In WCF when a channel is created in code you can specify the endpoint,
so we only need to created different endpoints depending of the site where the the .xap file was download.

The proposed changes will be:

For example if you create services in your App.xaml.cs method Application_Startup
Then you can change your code for something like:

string url = "http://" + HtmlPage.Document.DocumentUri.Host + "/MyService.svc";
EndpointAddress endpoint = new EndpointAddress(url);
var service = new MyService(new ChannelFactory<IMyService>("*").CreateChannel(endpoint)));

This will allow you to just deploy your application to either Staging or Production environment
in Azure with no more code or config file changes.