以编程方式从wcf配置文件中的单独服务获取基址的值

时间:2014-07-09 09:29:05

标签: c# wcf

说我有以下wcf配置文件

<services>
  <service name="Service" behaviorConfiguration="Default">
    <endpoint address="rest" behaviorConfiguration="Default" binding="webHttpBinding" bindingConfiguration="WebBinding" contract="CaptureService"/>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8501/service/service1.svc"/>
      </baseAddresses>
    </host>
  </service>
  <service name="otherService" behaviorConfiguration="Default">
    <endpoint address="start" behaviorConfiguration="Default" binding="webHttpBinding" bindingConfiguration="WebBinding" contract="CaptureService"/>
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8501/service/service2.svc"/>
      </baseAddresses>
    </host>
  </service>
</services>

如何循环访问配置以检索baseAdresses的值? 这是我想要的方法:

    public ServiceHost()
    {
        //read the config here

        this.service = svcType;
        this.scheme = new UriSchemeKeyedCollection(//list of values here);

        //add certain behaviours
        base.InitializeDescription(this.service, this.scheme);
        this.Description.Behaviors.Add(this);
    }

我觉得我可能会以完全错误的方式解决这个问题。有没有人看到任何内在的错误?

1 个答案:

答案 0 :(得分:5)

您可以阅读配置文件,选择system.serviceModel部分,然后转到services及其host元素,最后转到baseAddresses

private static Uri[] GetBaseAddresses()
{
    // Get the application configuration file.
    // TODO: Might be adjusted for WCF hosted / web.config
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    // Get the collection of the section groups.
    var sectionGroups = config.SectionGroups;

    // Get the serviceModel section
    var serviceModelSection = sectionGroups.OfType<ServiceModelSectionGroup>().SingleOrDefault();

    // Check if serviceModel section is configured
    if (serviceModelSection == null)
        throw new ArgumentNullException("Configuration section 'system.serviceModel' is missing.");

    // Get base addresses
    return (from ServiceElement service in serviceModelSection.Services.Services
            from BaseAddressElement baseAddress in service.Host.BaseAddresses
            select new Uri(baseAddress.BaseAddress)).ToArray();
}

然后简单地使用构造函数中的方法:

this.scheme = new UriSchemeKeyedCollection(GetBaseAddresses());