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.

public
class ErrorBehavior : BehaviorExtensionElement, IServiceBehavior
{
    #region BehaviorExtensionElement

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

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

    #endregion

    #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;
            channelDispatcher.ErrorHandlers.Add(errorHandler);
        }
     }

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
    {
    }

    #endregion
}

And here is a part of the configuration file.

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

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