5

我想在 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来安装错误扩展。这是强制性的,还是我的方法也应该有效?

4

3 回答 3

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

在调用 .Open() 之前插入设置主机时的行为:

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

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

于 2013-04-18T18:28:14.073 回答
0

根据这篇文章IErrorHandler 实例是通过行为添加的。没有提及任何其他机制,例如您的示例。

于 2012-08-22T23:31:05.847 回答
0

菲尔,我相信杰伊的回答遵循您提供的 MSDN 链接上的说明,他只注释掉了胆量并保留了本次讨论的必要内容。然后,他通过最后一行代码添加/注册 ServiceBehavior(以及 IErrorHandler)。

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

于 2014-06-02T08:23:58.280 回答