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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With