WCF 第五章 行为 为服务终结点行为实现一个消息检测器

本文介绍了一个自定义消息检测器的实现方法,通过在服务终结点行为中加入myMessageInspector类来记录消息,适用于诊断和跟踪需求。myMessageInspector实现了IDispatchMessageInspector接口,并在消息发送和接收时打印详细信息。

列表5.23通过将一个终结点发送的和接收的每条消息打印出来来实现一个日志功能。代码显示了从一个终结点行为调用的消息检测器。这也是自定义寄宿服务如何将终结点行为手动添加到服务描述中去。

提示  为跟踪实现自定义行为

实际应用时,如果你需要为诊断的目的实现一个消息检测器,请查看第十章”异常处理”以获得跟踪技术。

  myMessageInspector 类实现了IDispatchMessageInspector接口。在它的BeforeSendRequest和AfterReceiveReply方法中它把消息打印到控制台。类myEndpointBehavior实现了IEndpointBehavior接口。在它的AddDispatchBehavior方法中它把myMessageInspector类添加到消息检测器列表中以便于可以被每一条消息调用。最后,主程序将myEndpointBehavior类添加到所有终结点的行为列表中。注意因为服务也有一个MEX终结点,对终结点的请求和回复也会被myEndpointBehavior打印出来。

列表5.23 在一个服务终结点行为中的消息检测器

    public class myEndpointBehavior : IEndpointBehavior
    {
        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new myMessageInspector());
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }
    }
    public class myMessageInspector : IDispatchMessageInspector
    {
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, 

System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            Console.WriteLine(request.ToString());
            return request;
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            Console.WriteLine(reply.ToString());
        }
    }
    [ServiceContract]
    public interface IStockService
    {
        [OperationContract]
        double GetPrice(string ticker);
    }

    public class StockService : IStockService
    {
        public double GetPrice(string ticker)
        {
            return 94.85;
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值