Загрузка раздела конфигурации System.ServiceModel с помощью ConfigurationManager

StackOverflow https://stackoverflow.com/questions/19589

Вопрос

Используя C#.NET 3.5 и WCF, я пытаюсь записать часть конфигурации WCF в клиентском приложении (имя сервера, к которому подключается клиент).

Очевидный способ — использовать ConfigurationManager загрузить раздел конфигурации и записать нужные мне данные.

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

Кажется, всегда возвращает ноль.

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

Работает отлично.

Раздел конфигурации присутствует в App.config, но по какой-то причине ConfigurationManager отказывается загружать system.ServiceModel раздел.

Я хочу избежать ручной загрузки файла xxx.exe.config и использования XPath, но если мне придется прибегнуть к этому, я так и сделаю.Просто похоже на хак.

Какие-либо предложения?

Это было полезно?

Решение

А <system.serviceModel> элемент предназначен для раздела конфигурации группа, а не раздел.Вам нужно будет использовать System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup() чтобы собрать всю группу.

Другие советы

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

Кажется, работает хорошо.

Это то, что я искал, спасибо @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;
    }

GetSectionGroup() не поддерживает параметры (в рамках платформы 3.5).

Вместо этого используйте:

Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup group = System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup(config);

Благодаря другим авторам я разработал эту функцию для получения URI именованной конечной точки.Он также создает список используемых конечных точек и фактический файл конфигурации, который использовался при отладке:

Private Function GetEndpointAddress(name As String) As String
    Debug.Print("--- GetEndpointAddress ---")
    Dim address As String = "Unknown"
    Dim appConfig As Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
    Debug.Print("app.config: " & appConfig.FilePath)
    Dim serviceModel As ServiceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(appConfig)
    Dim bindings As BindingsSection = serviceModel.Bindings
    Dim endpoints As ChannelEndpointElementCollection = serviceModel.Client.Endpoints
    For i As Integer = 0 To endpoints.Count - 1
        Dim endpoint As ChannelEndpointElement = endpoints(i)
        Debug.Print("Endpoint: " & endpoint.Name & " - " & endpoint.Address.ToString)
        If endpoint.Name = name Then
            address = endpoint.Address.ToString
        End If
    Next
    Debug.Print("--- GetEndpointAddress ---")
    Return address
End Function
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top