Install IErrorHandler on WCF Service Channel Manager

I would like to install the IErrorHandler implementation in the WCF service.

I am currently using this code, which seems to do nothing:

logServiceHost = new ServiceHost(typeof(Logger));
logServiceHost.AddServiceEndpoint(typeof(ILogger), binding, address);

// Implementation of IErrorHandler.
var errorHandler = new ServiceErrorHandler();

logServiceHost.Open();

// Add error handler to all channel dispatchers.
foreach (ChannelDispatcher dispatcher in logServiceHost.ChannelDispatchers)
{
    dispatcher.ErrorHandlers.Add(errorHandler);
}

All the code examples I've seen (including in the book I use for WCF) show how to set the error extension using the custom IServiceBehavior. Is this mandatory, or should my approach work as well?

+5
source share
3 answers

Here's how I got it to work:

Create a class that implements IServiceBehavior. The behavior of the service will add your class that implements IErrorHandler:

public class GlobalExceptionHandlerBehavior : IServiceBehavior
{

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

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
    {
        foreach (ChannelDispatcherBase dispatcherBase in
             serviceHostBase.ChannelDispatchers)
        {
            var channelDispatcher = dispatcherBase as ChannelDispatcher;
            if (channelDispatcher != null)
                channelDispatcher.ErrorHandlers.Add(new ServiceErrorHandler());
        }

    }

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

Paste the host configuration behavior before calling .Open ():

logServiceHost.Description.Behaviors.Insert(0, new GlobalExceptionHandlerBehavior());

ErrorHandler() ServiceErrorHandler, . xml .

+5

IErrorHandler . , .

0

, , Jay MSDN, , . / ServiceBehavior (, , IErrorHandler) .

- , . .

0

All Articles