Using BehaviorExtensionElement and IServiceBehavior to Add an IErrorHandler to a WCF Service

By Michael Detras

We can add an IErrorHandler to a WCF service so that it takes care for exception handling for the said service. We can add it via the configuration file by using BehaviorExtensionElement and IServiceBehavior.

Here is the class definition. In the ApplyDispatchBehavior, we can add our ErrorHandler object. The ErrorHandler class is not shown here. You can easily create one by implementing the IErrorHandler interface.

class ErrorBehavior : BehaviorExtensionElement, IServiceBehavior
    #region BehaviorExtensionElement

    public override Type BehaviorType
        get { return typeof(ErrorBehavior); }

    protected override object CreateBehavior()
         return new ErrorBehavior();


    #region IServiceBehavior Members

    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
         var errorHandler = new ErrorHandler();
        foreach (var channelDispatcherBase in serviceHostBase.ChannelDispatchers)
             var channelDispatcher = channelDispatcherBase as ChannelDispatcher;

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)


And here is a part of the configuration file.

    <behavior name="defaultServiceBehavior">          
       <serviceMetadata httpGetEnabled="true" />          
      <serviceDebug includeExceptionDetailInFaults="false" />
        <windowsAuthentication allowAnonymousLogons="false" includeWindowsGroups="true" />
    <add name="errorBehavior"
type="ServiceContracts.ErrorBehavior, ServiceContracts, Version=, Culture=neutral, PublicKeyToken=null"/>

Using BehaviorExtensionElement and IServiceBehavior to Add an IErrorHandler to a WCF Service  (4885 Views)