使用ConfigurationManager加载System.ServiceModel配置部分

时间:2020-03-05 18:41:27  来源:igfitidea点击:

使用C.NET 3.5和WCF,我试图在客户端应用程序(客户端连接到的服务器的名称)中写出一些WCF配置。

一种明显的方法是使用ConfigurationManager来加载配置部分并写出我需要的数据。

var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel");

似乎总是返回null。

var serviceModelSection = ConfigurationManager.GetSection("appSettings");

完美的作品。

配置部分位于App.config中,但是由于某些原因,ConfigurationManager拒绝加载system.ServiceModel部分。

我想避免手动加载xxx.exe.config文件并使用XPath,但是如果需要的话,我会这样做。似乎有点hack。

有什么建议?

解决方案

回答

http://mostlytech.blogspot.com/2007/11/programmatically-enumerate-wcf.html

// Automagically find all client endpoints defined in app.config
ClientSection clientSection = 
    ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;

ChannelEndpointElementCollection endpointCollection =
    clientSection.ElementInformation.Properties[string.Empty].Value as     ChannelEndpointElementCollection;
List<string> endpointNames = new List<string>();
foreach (ChannelEndpointElement endpointElement in endpointCollection)
{
    endpointNames.Add(endpointElement.Name);
}
// use endpointNames somehow ...

似乎运作良好。

回答

<system.serviceModel>元素用于配置节组,而不是节。我们需要使用System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup()来获取整个组。

回答

这就是我一直在寻找的东西,感谢@marxidad提供的指针。

public static string GetServerName()
    {
        string serverName = "Unknown";

        Configuration appConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(appConfig);
        BindingsSection bindings = serviceModel.Bindings;

        ChannelEndpointElementCollection endpoints = serviceModel.Client.Endpoints;

        for(int i=0; i<endpoints.Count; i++)
        {
            ChannelEndpointElement endpointElement = endpoints[i];
            if (endpointElement.Contract == "MyContractName")
            {
                serverName = endpointElement.Address.Host;
            }
        }

        return serverName;
    }