Since I’m using extensively the Wcf castle proxy generator today I needed to add a new feature, I need to be able to specify via code the base address of the various services. I know that my service are usually in https://www.mysite.com/services/ but I want to be able to specify via code the base address, especially to target different environment, like production and test.
To keep everything simple, I created a simple static property on the proxy creator
This property is usually set by the facility, so I’m able to configure the base address directly from facility configuration.
But I’m also able to change it by code, this permits me to change it at runtime. All the dirty work is made by the WcfProxyActivator, that needs to use a little bit of reflection to create the service.
Now if I need to create a proxy that point to the current service address specified in web.config I use this code
But if I want the proxy to point to a different address I need this piece of code.
What I need to do is knowing the original address of the service, and changing the base address, keeping only the name of the service.
Knowing the original address can be tricky, what I got in the proxy creator is the name of the endpoint of the service and I need to know the address. The solution is reading the configuration file with the ConfigurationManager that can be queried for the system.serviceModel/client section, that contains the configuration of services. This section has a list of endpoints, and you can use a little bit of LINQ to the one you are creating (remember that you have the name of the endpoint). The result of the LINQ query is an object of type ChannelEndpointElement that contains endpoint configuration, and from it you can fine service address in the Address property. Now you only need to create a new EndpointAddress with the new address of the service, and pass it to CreateChannel method. And everything works as expected.