2014-09-19 48 views
0

WCF配置增强WCF配置增强

背景:

app.configweb.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

回答

1

要改变,你需要知道EndPointName和ContractName端点地址。这个值可以在WCF配置中的配置文件中找到。那么你可以使用下面的代码:

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)); 
     } 
    } 

快乐编码!

+0

谢谢你看起来不错 – user1497197 2014-09-19 17:53:27