Pergunta

Usando C# .NET 3.5 e WCF, estou tentando escrever algumas configurações do WCF em um aplicativo cliente (o nome do servidor ao qual o cliente está se conectando).

A maneira óbvia é usar ConfigurationManager para carregar a seção de configuração e escrever os dados necessários.

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

Parece sempre retornar nulo.

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

Funciona perfeitamente.

A seção de configuração está presente no App.config, mas por algum motivo ConfigurationManager se recusa a carregar o system.ServiceModel seção.

Quero evitar carregar manualmente o arquivo xxx.exe.config e usar XPath, mas se precisar recorrer a isso, o farei.Parece um pouco um hack.

Alguma sugestão?

Foi útil?

Solução

O <system.serviceModel> elemento é para uma seção de configuração grupo, não uma seção.Você precisará usar System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup() para pegar todo o grupo.

Outras dicas

http://mostlytech.blogspot.com/2007/11/programmaticamente-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 ...

Parece funcionar bem.

Era isso que eu procurava, graças ao @marxidad pela indicação.

    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() não suporta nenhum parâmetro (na estrutura 3.5).

Em vez disso, use:

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

Graças aos outros postadores, esta é a função que desenvolvi para obter o URI de um endpoint nomeado.Ele também cria uma lista dos endpoints em uso e qual arquivo de configuração real estava sendo usado durante a depuração:

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
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top