WCF配置增强
本文关键字:增强 配置 WCF | 更新日期: 2023-09-27 18:22:36
WCF配置增强
背景:
在app.config
或web.config
中,可以在中定义配置条目
<appSettings>...</appSettings>
像这样:
<add key="MyKey" value="%SomeEnvironmentVariable%"/>
此后,为了检索与MyKey
相关联的值,可以使用以下两行代码:
string raw = ConfigurationManager.AppSettings[“MyKey”];
string cooked = (raw == null) ? null : Environment.ExpandEnvironmentVariables(raw);
问题:
有没有一种方法可以对WCF服务配置进行同样的操作,例如:
<system.serviceModel>
. . .
<services>
<service name="..." ...>
. . .
<endpoint
address="%MyEndPointAddress%" ... />
. . .
</service>
</services>
</system.serviceModel>
任何知识都将不胜感激。
--Avi
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));
}
}
编码快乐!