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

Ric*_*dMc 2 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>
Run Code Online (Sandbox Code Playgroud)

如何循环访问配置以检索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);
    }
Run Code Online (Sandbox Code Playgroud)

我觉得我可能会以完全错误的方式解决这个问题.有没有人看到任何本质上错误的东西?

Her*_*rdo 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();
}
Run Code Online (Sandbox Code Playgroud)

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

this.scheme = new UriSchemeKeyedCollection(GetBaseAddresses());
Run Code Online (Sandbox Code Playgroud)