IOperationBehavior–How to customize behaviors for the WCF operation?

Posted on December 22, 2010 by

1


IOperationBehavior which is located in System.ServiceModel.Description assembly allows to extend the behaviors of operations for both the client and the server sides.

Its interface contains 4 methods:

public interface IOperationBehavior
{
    void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters);
    void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation);
    void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation);
    void Validate(OperationDescription operationDescription);
}

Your custom implementation of IOperationBehavior can be added in two ways:

1. By adding your custom implementation of IOperationBehavior to the list of operations behaviors on the ChannelFactory/ ServiceHost.

On the client side:

foreach (var operation in channelFactory.Endpoint.Contract.Operations)
{
    operation.Behaviors.Add(MyOperationBehavior());
}

On the server side:

 foreach (var endpoint in serviceHost.Description.Endpoints)
 {
    foreach (var operation in endpoint.Contract.Operations)
    {
        operation.Behaviors.Add(new MyOperationBehavior());
    }
 }

2. By Implementing the IOperationBehavior interface also as an attribute and adding this attribute to the operations in your WCF contract:

public class MyOperationBehavior : Attribute, IOperationBehavior
{
    #region IOperationBehavior Members

    public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
        ...
    }

    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
        ...
    }

    public void Validate(OperationDescription operationDescription)
    {
    }

    #endregion
}

[ServiceContract]
public interface ICalc
{
    [OperationContract]
    [MyOperationBehavior]
    int Add(int x, int y);
}

Advertisements
Posted in: WCF Extensions