在WCF服务通道调度程序上安装IErrorHandler

时间:2012-08-22 09:44:56

标签: c# .net wcf

我想在WCF服务上安装IErrorHandler的实现。

我目前正在使用此代码,它似乎没有做任何事情:

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);
}

我见过的所有代码示例(包括在我用于WCF的书中)都显示了如何使用自定义创建的 IServiceBehavior 来安装错误扩展。这是强制性的,或者我的方法也应该有效吗?

3 个答案:

答案 0 :(得分:5)

以下是我如何使用它:

创建一个实现IServiceBehavior的类。服务行为将添加实现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)
    {
    }
}

在设置主机befor时调用行为。打开():

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

然后,您应该能够在ServiceErrorHandler类中的ErrorHandler()方法中放置一个断点,它应该为您打破。这不需要xml配置,完全由代码驱动。

答案 1 :(得分:0)

根据this article IErrorHandler实例是通过行为添加的。没有提到任何其他机制,例如你的例子。

答案 2 :(得分:0)

菲尔,我相信杰伊的回答是按照你提供的MSDN链接上的说明进行的,他只是评论了这些内容,并保留了讨论的必要条件。然后,他通过最后一行代码添加/注册ServiceBehavior(以及IErrorHandler)。

如果你问我,他的答案是对已发布问题的解决方案。我刚刚在一个最小的自托管项目中验证了它。