Sistema De Carga.ServiceModel de la sección de configuración utilizando ConfigurationManager

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

Pregunta

El Uso De C# .NET 3.5 y WCF, estoy tratando de escribir un vistazo a algunos de la configuración de WCF en una aplicación de cliente (el nombre del servidor al que el cliente se conecta a).

La manera más obvia es el uso de ConfigurationManager para cargar la sección de configuración y escribir los datos que necesito.

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

Aparece siempre devuelve null.

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

Funciona a la perfección.

La sección de configuración está presente en la Aplicación.configuración, pero por alguna razón ConfigurationManager se niega a cargar el system.ServiceModel sección.

Quiero evitar que se carga manualmente el xxx.exe.archivo de configuración y el uso de XPath, pero si tengo que recurrir a la que voy.Apenas se parece como un poco de un hack.

Alguna sugerencia?

¿Fue útil?

Solución

El <system.serviceModel> es el elemento en la sección de configuración grupo, no una sección.Usted necesitará utilizar System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup() a todo el grupo.

Otros consejos

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

Parece funcionar bien.

Esto es lo que estaba buscando gracias a @marxidad para el puntero.

    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() no admite ningún parámetros (bajo framework 3.5).

En su lugar utilizar:

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

Gracias a los otros posters esta es la función que he desarrollado para obtener la URI de un nombre de estación.También crea una lista de las estaciones en uso y que real archivo de configuración estaba siendo utilizado cuando la depuración:

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 bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top