IEndpointBehavior–How to add behavior on a specific endpoint?

Posted on April 30, 2011 by


IEndpointBehavior, as its name implies, allows you to add your custom behaviors on the service endpoints both on the client, and on the server.

The IEndpointBehavior interface is very similar to the IOperationBehavior interface which was described in the previous post

The methods are similar (and therefore I wont elaborate on them once more), but their signature is different, mostly because IEndpointBehavior receives the endpoint on which the behavior is applied, and the ClientRuntime and EndpointDispatcher objects.

public interface IEndpointBehavior 
    void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters);
    void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime);
    void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher);
    void Validate(ServiceEndpoint endpoint);

When you add your custom implementation of IEndpointBehavior you can apply it on runtime on a specific endpoint , in two ways:

1. Configure the behavior in the configuration file under <endpointbehaviors> section:

    <endpoint address="http://localhost:8000/MySample/" 
              contract="WCFSample.service.IPing" />
      <behavior name="MyBehavior">
      <add name="myEndpointBehavior" 
           type="WCFSample.MyEndpointBehavior, MyEndpointBehavior, Version=, Culture=neutral, PublicKeyToken=null" />

2. Programmatically add your custom implementation on the ServiceHost (on the server) or on the ChannelFactory (on the client):

On the client:

channelFactory.Endpoint.Behaviors.Add(new MyEndpointBehavior());

On the server:

foreach (var endpoint in serviceHost.Description.Endpoints)
    endpoint.Behaviors.Add(new MyEndpointBehavior());

Note that the behavior can not be added as an attribute, since it is applied on endpoints.

IEndpointBehavior Sample

In this sample we use the IEndpointBehavior  to add an inspector on the client:

For more information on MessageInspector, see –

internal class MyEndpointBehavior: IEndpointBehavior
    public void AddBindingParameters(ServiceEndpoint serviceEndpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)

    { }

    public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint, System.ServiceModel.Dispatcher.ClientRuntime behavior)
        behavior.MessageInspectors.Add(new MyClientMessageInspector());

    public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
    { }

    public void Validate(ServiceEndpoint serviceEndpoint)
    { }

Posted in: WCF Extensions