Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Installing an IErrorHandler on a WCF service channel dispatcher

Tags:

c#

.net

wcf

I would like to install an implementation of IErrorHandler on a WCF service.

I am currently using this code, which does not seem to do anything:

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 code examples i've seen (including in the book i am using for WCF) shows how to install an error extension by using a custom created IServiceBehavior. Is this mandatory, or my approach should work as well?

like image 571
lysergic-acid Avatar asked Aug 22 '12 09:08

lysergic-acid


1 Answers

Here is how I got this to work:

Create a class the implements IServiceBehavior. The service behavior 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)
    {
    }
}

Insert the behavior when setting up your host befor calling .Open():

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

You should then be able to put a break point inside your ErrorHandler() method within your ServiceErrorHandler class and it should break for you. This required no xml configuration and is completely code driven.

like image 59
Jay Avatar answered Nov 15 '22 12:11

Jay