IContractBehavior Interface
Definição
Implementa métodos que podem ser usados para estender o comportamento de tempo de execução de um contrato em um serviço ou aplicativo cliente.Implements methods that can be used to extend run-time behavior for a contract in either a service or client application.
public interface class IContractBehavior
public interface IContractBehavior
type IContractBehavior = interface
Public Interface IContractBehavior
- Derivado
Exemplos
O exemplo de código a seguir pressupõe uma IInstanceProvider implementação personalizada chamada ObjectProviderBehavior que fornece um comportamento "singleton"; ela sempre retorna a mesma instância de serviço e não a recicla.The following code example assumes a custom IInstanceProvider implementation called ObjectProviderBehavior that provides a "singleton" behavior; it always returns the same service instance and does not recycle it.
Para inserir a personalização do provedor de instância, o exemplo mostra como implementar um atributo personalizado ( SingletonBehaviorAttribute ) que implementa IContractBehavior para inserir o provedor de instância de serviço personalizado.To insert the instance provider customization, the example shows how to implement a custom attribute (SingletonBehaviorAttribute) that implements IContractBehavior to insert the custom service instance provider. Ele também implementa IContractBehaviorAttribute , que associa seu uso ao ISampleService contrato.It also implements IContractBehaviorAttribute, which binds its use to the ISampleService contract.
public class SingletonBehaviorAttribute : Attribute, IContractBehaviorAttribute, IContractBehavior
{
#region IContractBehaviorAttribute Members
public Type TargetContract
{
get { return typeof(ISampleService); }
}
#endregion
#region IContractBehavior Members
public void AddBindingParameters(ContractDescription description, ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection parameters)
{
return;
}
public void ApplyClientBehavior(ContractDescription description, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
return;
}
public void ApplyDispatchBehavior(ContractDescription description, ServiceEndpoint endpoint, DispatchRuntime dispatch)
{
dispatch.InstanceProvider = new ObjectProviderBehavior("Custom ObjectProviderBehavior constructor.");
}
public void Validate(ContractDescription description, ServiceEndpoint endpoint)
{
return;
}
#endregion
}
Public Class SingletonBehaviorAttribute
Inherits Attribute
Implements IContractBehaviorAttribute, IContractBehavior
#Region "IContractBehaviorAttribute Members"
Public ReadOnly Property TargetContract() As Type Implements IContractBehaviorAttribute.TargetContract
Get
Return GetType(ISampleService)
End Get
End Property
#End Region
#Region "IContractBehavior Members"
Public Sub AddBindingParameters(ByVal description As ContractDescription, ByVal endpoint As ServiceEndpoint, ByVal parameters As System.ServiceModel.Channels.BindingParameterCollection) Implements IContractBehavior.AddBindingParameters
Return
End Sub
Public Sub ApplyClientBehavior(ByVal description As ContractDescription, ByVal endpoint As ServiceEndpoint, ByVal clientRuntime As ClientRuntime) Implements IContractBehavior.ApplyClientBehavior
Return
End Sub
Public Sub ApplyDispatchBehavior(ByVal description As ContractDescription, ByVal endpoint As ServiceEndpoint, ByVal dispatch As DispatchRuntime) Implements IContractBehavior.ApplyDispatchBehavior
dispatch.InstanceProvider = New ObjectProviderBehavior("Custom ObjectProviderBehavior constructor.")
End Sub
Public Sub Validate(ByVal description As ContractDescription, ByVal endpoint As ServiceEndpoint) Implements IContractBehavior.Validate
Return
End Sub
#End Region
End Class
Comentários
Implemente a IContractBehavior interface para modificar, examinar ou estender algum aspecto da execução em todo o contrato no nível do aplicativo.Implement the IContractBehavior interface to modify, examine, or extend some aspect of contract-wide execution at the application level. Ao contrário dos IServiceBehavior IEndpointBehavior objetos e, IContractBehavior os objetos não podem ser adicionados ao tempo de execução usando um arquivo de configuração de aplicativo; eles só podem ser adicionados programaticamente ou usando um atributo.Unlike IServiceBehavior and IEndpointBehavior objects, IContractBehavior objects cannot be added to the runtime using an application configuration file; they can only be added programmatically or using an attribute.
Para obter mais informações sobre como escolher entre os comportamentos de serviço, ponto de extremidade e contrato, consulte Configurando e estendendo o tempo de execução com comportamentos.For more information about choosing between service, endpoint, and contract behaviors, see Configuring and Extending the Runtime with Behaviors.
Use o AddBindingParameters método para fornecer elementos de associação com dados personalizados para dar suporte ao comportamento.Use the AddBindingParameters method to provide binding elements with custom data to support the behavior.
Use o ApplyClientBehavior método para modificar, examinar ou inserir extensões em um contrato em um aplicativo cliente.Use the ApplyClientBehavior method to modify, examine, or insert extensions to a contract in a client application.
Use o ApplyDispatchBehavior método para modificar, examinar ou inserir extensões em um contrato em um aplicativo de serviço.Use the ApplyDispatchBehavior method to modify, examine, or insert extensions to a contract in a service application.
Use o Validate método para garantir que um contrato possa dar suporte a um recurso específico.Use the Validate method to ensure that a contract can support a particular feature.
IContractBehavior os objetos podem fazer uso de qualquer um desses métodos, mas geralmente apenas um é importante; nesses casos, os métodos não utilizados podem retornar sem nenhum valor.IContractBehavior objects can make use of any of these methods, but often only one is important; in such cases, the unused methods can return without any value.
Observação
Todos os IContractBehavior métodos passam System.ServiceModel.Description.ContractDescription e System.ServiceModel.Description.ServiceEndpoint como parâmetros.All of the IContractBehavior methods pass System.ServiceModel.Description.ContractDescription and System.ServiceModel.Description.ServiceEndpoint as parameters. Esses parâmetros são para exame; Se você modificar os objetos, o comportamento de execução será indefinido.These parameters are for examination; if you modify the objects the execution behavior is undefined.
IContractBehavior os tipos podem ser usados no serviço ou no cliente, ou em ambos.IContractBehavior types can be used on either the service or the client, or both. Para executar uma tarefa de personalização no serviço, o IContractBehavior objeto deve ser adicionado à Behaviors propriedade antes da construção do tempo de execução do serviço, que ocorre quando o ICommunicationObject.Open método é chamado no System.ServiceModel.ServiceHost objeto.To perform a customization task on the service, the IContractBehavior object must be added to the Behaviors property prior to the construction of the service runtime, which occurs when the ICommunicationObject.Open method is called on the System.ServiceModel.ServiceHost object. Há duas maneiras de fazer isso.There are two ways to do this.
O primeiro método é adicionar programaticamente o comportamento do contrato personalizado à Behaviors propriedade antes do ponto em que o ICommunicationObject.Open método é chamado no System.ServiceModel.ServiceHost objeto.The first method is to programmatically add the custom contract behavior to the Behaviors property prior to the point when the ICommunicationObject.Open method is called on the System.ServiceModel.ServiceHost object. Quando aplicado dessa forma, o comportamento é aplicado a todas as mensagens que fluem pelo contrato em qualquer ponto de extremidade.When applied this way, the behavior is applied for all messages flowing through that contract on any endpoint.
Observação
O comportamento é aplicado a todos os contratos do mesmo tipo.The behavior is applied to all contracts of the same type. Por exemplo, se você adicionar programaticamente o mesmo tipo de contrato a mais de um ponto de extremidade, o comportamento modificará todos os pontos de extremidades que se referem ao mesmo objeto de contrato.For example, if you programmatically add the same contract type to more than one endpoint, the behavior modifies all endpoints that refer to the same contract object.
O segundo método é criar um atributo personalizado que implemente IContractBehavior e aplique isso a:The second method is to create a custom attribute that implements IContractBehavior and apply that to:
Uma interface de contrato.A contract interface. Nesse caso, o comportamento é aplicado a todos os contratos desse tipo em qualquer ponto de extremidade.In this case, the behavior is applied to all contracts of that type in any endpoint.
Uma classe de serviço.A service class. Nesse caso, o comportamento é aplicado a todos os pontos de extremidade, independentemente do contrato.In this case, the behavior is applied to all endpoints regardless of contract.
Uma classe de retorno de chamada.A callback class. Nesse caso, o comportamento é aplicado ao ponto de extremidade do cliente duplex.In this case, the behavior is applied to the duplex client's endpoint.
O comportamento da segunda abordagem varia ligeiramente se o atributo personalizado também implementa System.ServiceModel.Description.IContractBehaviorAttribute .The behavior of the second approach varies slightly if the custom attribute also implements System.ServiceModel.Description.IContractBehaviorAttribute. Nesse caso, o comportamento é o seguinte:In this case, the behavior is as follows:
Uma interface de contrato.A contract interface. Nesse caso, o comportamento é aplicado a todos os contratos desse tipo em qualquer ponto de extremidade e Windows Communication Foundation (WCF) ignora o valor da IContractBehaviorAttribute.TargetContract propriedade.In this case, the behavior is applied to all contracts of that type in any endpoint and Windows Communication Foundation (WCF) ignores the value of the IContractBehaviorAttribute.TargetContract property.
Uma classe de serviço.A service class. Nesse caso, o comportamento é aplicado somente a pontos de extremidade do contrato que é o valor da IContractBehaviorAttribute.TargetContract propriedade.In this case, the behavior is applied only to endpoints the contract of which is the value of the IContractBehaviorAttribute.TargetContract property.
Uma classe de retorno de chamada.A callback class. Nesse caso, o comportamento é aplicado ao ponto de extremidade do cliente duplex e o WCF ignora o valor da IContractBehaviorAttribute.TargetContract propriedade.In this case, the behavior is applied to the duplex client's endpoint and WCF ignores the value of the IContractBehaviorAttribute.TargetContract property.
Para executar a tarefa de personalização no cliente para o qual ele se destina, o IContractBehavior objeto deve ser adicionado à Behaviors propriedade antes da construção do tempo de execução do cliente, que ocorre quando ChannelFactory<TChannel>.CreateChannel é chamado.To perform the customization task on the client for which it is intended, the IContractBehavior object must be added to the Behaviors property prior to the construction of the client runtime, which occurs when ChannelFactory<TChannel>.CreateChannel is called. Há duas maneiras de fazer isso:There are two ways to do this:
Adicione programaticamente o comportamento do contrato personalizado à Behaviors propriedade antes do ponto em que o ChannelFactory<TChannel>.CreateChannel é chamado.Programmatically add the custom contract behavior to the Behaviors property prior to the point when the ChannelFactory<TChannel>.CreateChannel is called.
Crie um atributo personalizado que também implementa IContractBehavior .Create a custom attribute that also implements IContractBehavior.
Para obter mais informações sobre como adicionar tipos programaticamente IContractBehavior ao aplicativo cliente ou de serviço, consulte Configurando e estendendo o tempo de execução com comportamentos.For more information on programmatically adding IContractBehavior types to either the client or service application, see Configuring and Extending the Runtime with Behaviors.
Métodos
| AddBindingParameters(ContractDescription, ServiceEndpoint, BindingParameterCollection) |
Configura quaisquer elementos de associação para dar suporte ao comportamento de contrato.Configures any binding elements to support the contract behavior. |
| ApplyClientBehavior(ContractDescription, ServiceEndpoint, ClientRuntime) |
Implementa uma modificação ou extensão do cliente em todo um contrato.Implements a modification or extension of the client across a contract. |
| ApplyDispatchBehavior(ContractDescription, ServiceEndpoint, DispatchRuntime) |
Implementa uma modificação ou extensão do cliente em todo um contrato.Implements a modification or extension of the client across a contract. |
| Validate(ContractDescription, ServiceEndpoint) |
Implemente para confirmar que o contrato e o ponto de extremidade são compatíveis com o comportamento de contrato.Implement to confirm that the contract and endpoint can support the contract behavior. |