2008-08-21 17 views
55

Usando C# .NET 3.5 y WCF, estoy tratando de escribir algo de la configuración de WCF en una aplicación cliente (el nombre del servidor al que se conecta el cliente).Cargando System.ServiceModel sección de configuración usando ConfigurationManager

La forma obvia es usar ConfigurationManager para cargar la sección de configuración y escribir los datos que necesito.

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

Parece que siempre devuelve nulo.

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

Funciona perfectamente.

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

Quiero evitar cargar manualmente el archivo xxx.exe.config y usar XPath, pero si tengo que recurrir a eso lo haré. Solo parece un truco.

¿Alguna sugerencia?

Respuesta

55

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.

+1

la línea confuso para endpointCollection = clientSection.ElementInformation.Properties [String.Empty] .Value como ChannelEndpointElementCollection; debe simplificarse a clientSection.Endpoints; – joedotnot

14

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; 
    } 
8

GetSectionGroup() no admite ningún parámetro (en el marco 3.5).

usar en su lugar:

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

Gracias a los otros carteles ésta es la función que he desarrollado para obtener el URI de un punto final denominado. También crea un listado de los puntos finales en uso y que estaba siendo utilizado el archivo de configuración actual al depurar:

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 
Cuestiones relacionadas