Reputation: 81
WCF Configuration Enhancement
Background:
In app.config
or web.config
one may define a config entry in:
<appSettings>...</appSettings>
like so:
<add key="MyKey" value="%SomeEnvironmentVariable%"/>
Thereafter in order to retrieve the value associated with MyKey
one may employ the following two lines of code:
string raw = ConfigurationManager.AppSettings[“MyKey”];
string cooked = (raw == null) ? null : Environment.ExpandEnvironmentVariables(raw);
Question:
Is there a way to do the same with the WCF service configuration, for example:
<system.serviceModel>
. . .
<services>
<service name="..." ...>
. . .
<endpoint
address="%MyEndPointAddress%" ... />
. . .
</service>
</services>
</system.serviceModel>
Any knowledge will be highly appreciated.
--Avi
Upvotes: 0
Views: 30
Reputation: 6805
To change endpoint address you will need to know EndPointName and ContractName. This values are found in your config file inside WCF configuration. Then you can use following code:
void SetNewEndpointAddress(string endpointName, string contractName, string newValue)
{
bool settingsFound = false;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ClientSection section = config.GetSection("system.serviceModel/client") as ClientSection;
foreach (ChannelEndpointElement ep in section.Endpoints)
{
if (ep.Name == endpointName && ep.Contract == contractName)
{
settingsFound = true;
ep.Address = new Uri(newValue);
config.Save(ConfigurationSaveMode.Full);
}
}
if (!settingsFound)
{
throw new Exception(string.Format("Settings for Endpoint '{0}' and Contract '{1}' was not found!", endpointName, contractName));
}
}
Happy coding!
Upvotes: 1