IServiceBehavior Interfaz

Definición

Proporciona un mecanismo para modificar o insertar las extensiones personalizadas en un servicio completo, incluso ServiceHostBase.Provides a mechanism to modify or insert custom extensions across an entire service, including the ServiceHostBase.

public interface class IServiceBehavior
public interface IServiceBehavior
type IServiceBehavior = interface
Public Interface IServiceBehavior
Derivado

Ejemplos

El ejemplo de código siguiente muestra el uso de un comportamiento de servicio, especificado en un archivo de configuración, para insertar un controlador de errores personalizado en una aplicación de servicio.The following code example shows the use of a service behavior specified in a configuration file to insert a custom error handler in a service application. En este ejemplo, el controlador de errores detecta todas las excepciones y las convierte en un error de SOAP GreetingFault personalizado que, a continuación, se devuelve al cliente.In this example, the error handler catches all exceptions and converts them into a custom GreetingFault SOAP fault that is then returned to the client.

La siguiente implementación IServiceBehavior no agrega ningún objeto de parámetro de enlace, agrega el objeto System.ServiceModel.Dispatcher.IErrorHandler personalizado a cada propiedad ChannelDispatcher.ErrorHandlers, y valida que cada operación del servicio a la que se aplica el comportamiento de servicio cuente con un atributo System.ServiceModel.FaultContractAttribute de tipo GreetingFault.The following IServiceBehavior implementation adds no binding parameter objects, adds the custom System.ServiceModel.Dispatcher.IErrorHandler object to each ChannelDispatcher.ErrorHandlers property, and validates that each operation of the service to which the service behavior is applied and has a System.ServiceModel.FaultContractAttribute of type GreetingFault.

// This behavior modifies no binding parameters.
#region IServiceBehavior Members
public void AddBindingParameters(
  ServiceDescription description, 
  ServiceHostBase serviceHostBase, 
  System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, 
  System.ServiceModel.Channels.BindingParameterCollection parameters
)
{
  return;
}

// This behavior is an IErrorHandler implementation and 
// must be applied to each ChannelDispatcher.
public void ApplyDispatchBehavior(ServiceDescription description, ServiceHostBase serviceHostBase)
{
  Console.WriteLine("The EnforceGreetingFaultBehavior has been applied.");
  foreach(ChannelDispatcher chanDisp in serviceHostBase.ChannelDispatchers)
  {
    chanDisp.ErrorHandlers.Add(this);      
  }
}

// This behavior requires that the contract have a SOAP fault with a detail type of GreetingFault.
public void Validate(ServiceDescription description, ServiceHostBase serviceHostBase)
{
  Console.WriteLine("Validate is called.");
  foreach (ServiceEndpoint se in description.Endpoints)
  {
    // Must not examine any metadata endpoint.
    if (se.Contract.Name.Equals("IMetadataExchange")
      && se.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex"))
      continue;
    foreach (OperationDescription opDesc in se.Contract.Operations)
    {
      if (opDesc.Faults.Count == 0)
        throw new InvalidOperationException(String.Format(
          "EnforceGreetingFaultBehavior requires a "  
          + "FaultContractAttribute(typeof(GreetingFault)) in each operation contract.  "
          + "The \"{0}\" operation contains no FaultContractAttribute.",
          opDesc.Name)
        );
      bool gfExists = false;
      foreach (FaultDescription fault in opDesc.Faults)
      {
        if (fault.DetailType.Equals(typeof(GreetingFault)))
        {
          gfExists = true;
          continue;
        }
      }
      if (gfExists == false)
      {
        throw new InvalidOperationException(
"EnforceGreetingFaultBehavior requires a FaultContractAttribute(typeof(GreetingFault)) in an operation contract."
        );
      }
    }
  }
}
#endregion
' This behavior modifies no binding parameters.
#Region "IServiceBehavior Members"
Public Sub AddBindingParameters(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase, ByVal endpoints As System.Collections.ObjectModel.Collection(Of ServiceEndpoint), ByVal parameters As System.ServiceModel.Channels.BindingParameterCollection) Implements IServiceBehavior.AddBindingParameters
  Return
End Sub

' This behavior is an IErrorHandler implementation and 
' must be applied to each ChannelDispatcher.
Public Sub ApplyDispatchBehavior(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase) Implements IServiceBehavior.ApplyDispatchBehavior
  Console.WriteLine("The EnforceGreetingFaultBehavior has been applied.")
  For Each chanDisp As ChannelDispatcher In serviceHostBase.ChannelDispatchers
    chanDisp.ErrorHandlers.Add(Me)
  Next chanDisp
End Sub

' This behavior requires that the contract have a SOAP fault with a detail type of GreetingFault.
Public Sub Validate(ByVal description As ServiceDescription, ByVal serviceHostBase As ServiceHostBase) Implements IServiceBehavior.Validate
  Console.WriteLine("Validate is called.")
  For Each se As ServiceEndpoint In description.Endpoints
    ' Must not examine any metadata endpoint.
    If se.Contract.Name.Equals("IMetadataExchange") AndAlso se.Contract.Namespace.Equals("http://schemas.microsoft.com/2006/04/mex") Then
      Continue For
    End If
    For Each opDesc As OperationDescription In se.Contract.Operations
      If opDesc.Faults.Count = 0 Then
        Throw New InvalidOperationException(String.Format("EnforceGreetingFaultBehavior requires a " & "FaultContractAttribute(typeof(GreetingFault)) in each operation contract.  " & "The ""{0}"" operation contains no FaultContractAttribute.", opDesc.Name))
      End If
      Dim gfExists As Boolean = False
      For Each fault As FaultDescription In opDesc.Faults
        If fault.DetailType.Equals(GetType(GreetingFault)) Then
          gfExists = True
          Continue For
        End If
      Next fault
      If gfExists = False Then
        Throw New InvalidOperationException("EnforceGreetingFaultBehavior requires a FaultContractAttribute(typeof(GreetingFault)) in an operation contract.")
      End If
    Next opDesc
  Next se
End Sub
#End Region

En este ejemplo, la clase de comportamiento también implementa System.ServiceModel.Configuration.BehaviorExtensionElement, lo que permite insertar el comportamiento de servicio mediante su uso en un archivo de configuración de la aplicación, como se muestra en el ejemplo de código siguiente.In this example, the behavior class also implements System.ServiceModel.Configuration.BehaviorExtensionElement, which enables the service behavior to be inserted by using it in an application configuration file, as the following code example demonstrates.

<configuration>
  <system.serviceModel>
    <services>
      <service 
        name="Microsoft.WCF.Documentation.SampleService"
        behaviorConfiguration="metaAndErrors">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/SampleService"/>
          </baseAddresses>
        </host>
        <endpoint
          address=""
          binding="wsHttpBinding"
          contract="Microsoft.WCF.Documentation.ISampleService"
         />
        <endpoint
          address="mex"
          binding="mexHttpBinding"
          contract="IMetadataExchange"
         />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="metaAndErrors">
          <serviceDebug includeExceptionDetailInFaults="true"/>
          <serviceMetadata httpGetEnabled="true"/>
          <enforceGreetingFaults />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <extensions>
      <behaviorExtensions>
        <add 
          name="enforceGreetingFaults" 
          type="Microsoft.WCF.Documentation.EnforceGreetingFaultBehavior, HostApplication, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"
        />
      </behaviorExtensions>
    </extensions>
  </system.serviceModel>
</configuration>

Comentarios

Implemente IServiceBehavior para modificar, examinar o extender algún aspecto de la ejecución de todo el servicio en el nivel de la aplicación.Implement IServiceBehavior to modify, examine, or extend some aspect of service-wide execution at the application level:

  • Utilice el método ApplyDispatchBehavior para cambiar los valores de propiedad en tiempo de ejecución o insertar objetos de extensión personalizados, como controladores de errores, interceptores de mensajes o parámetros, extensiones de seguridad y otros objetos de extensión personalizados.Use the ApplyDispatchBehavior method to change run-time property values or insert custom extension objects such as error handlers, message or parameter interceptors, security extensions, and other custom extension objects.

  • Utilice el Validate método para examinar la descripción antes de que Windows Communication Foundation (WCF) construya el servicio en ejecución para confirmar que se puede ejecutar correctamente.Use the Validate method to examine the description before Windows Communication Foundation (WCF) constructs the executing service to confirm that it can execute properly.

  • Utilice el método AddBindingParameters para pasar la información personalizada del servicio a un elemento de enlace de modo que pueda admitir correctamente el servicio.Use the AddBindingParameters method to pass to a binding element the custom information for the service so that it can support the service correctly.

Los objetos IServiceBehavior pueden utilizar cualquiera de estos métodos, pero a menudo sólo uno es importante; en ese caso, los métodos no usados pueden ser devueltos sin ningún valor.IServiceBehavior objects can make use of any of these methods, but often only one is important; in such cases the unused methods can return without a value.

Nota

Todos los métodos IServiceBehavior pasan System.ServiceModel.Description.ServiceDescription y los objetos System.ServiceModel.ServiceHostBase como parámetros.All of the IServiceBehavior methods pass System.ServiceModel.Description.ServiceDescription and System.ServiceModel.ServiceHostBase objects as a parameters. Este ServiceDescription parámetro se utiliza solo para realizar un examen, si se modifican estos objetos el comportamiento de la ejecución no estará definido.The ServiceDescription parameter is for examination only; if you modify these objects the execution behavior is undefined.

Para realizar la tarea de personalización prevista, el objeto IServiceBehavior debe agregarse a la propiedad Behaviors antes de la construcción del tiempo de ejecución del servicio.To perform the customization task for which it is intended, the IServiceBehavior object must be added to the Behaviors property prior to the construction of the service runtime. Existen tres formas de hacer esto:There are three ways to do this:

Entre los ejemplos de comportamientos de servicio de ServiceBehaviorAttribute WCF se incluyen System.ServiceModel.Description.ServiceThrottlingBehaviorel atributo System.ServiceModel.Description.ServiceDebugBehavior ,, System.ServiceModel.Description.ServiceMetadataBehavior y el comportamiento.Examples of service behaviors in WCF include the ServiceBehaviorAttribute attribute, the System.ServiceModel.Description.ServiceThrottlingBehavior, the System.ServiceModel.Description.ServiceDebugBehavior and the System.ServiceModel.Description.ServiceMetadataBehavior behavior.

Métodos

AddBindingParameters(ServiceDescription, ServiceHostBase, Collection<ServiceEndpoint>, BindingParameterCollection)

Proporciona la capacidad de pasar los datos personalizados a los elementos de enlace para admitir la implementación del contrato.Provides the ability to pass custom data to binding elements to support the contract implementation.

ApplyDispatchBehavior(ServiceDescription, ServiceHostBase)

Proporciona la capacidad de cambiar los valores de propiedad en tiempo de ejecución o insertar objetos de extensión personalizados, tales como controladores de error, interceptores de mensajes o parámetros, extensiones de seguridad, y otros objetos de extensión personalizados.Provides the ability to change run-time property values or insert custom extension objects such as error handlers, message or parameter interceptors, security extensions, and other custom extension objects.

Validate(ServiceDescription, ServiceHostBase)

Proporciona la capacidad de inspeccionar el host y la descripción del servicio para confirmar que este puede ejecutarse correctamente.Provides the ability to inspect the service host and the service description to confirm that the service can run successfully.

Se aplica a