WCF 第五章 行为 为服务终结点行为实现一个消息检测器
2010-12-13 14:57 DanielWise 阅读(723) 评论(1) 编辑 收藏 举报列表5.23通过将一个终结点发送的和接收的每条消息打印出来来实现一个日志功能。代码显示了从一个终结点行为调用的消息检测器。这也是自定义寄宿服务如何将终结点行为手动添加到服务描述中去。
提示 为跟踪实现自定义行为
实际应用时,如果你需要为诊断的目的实现一个消息检测器,请查看第十章”异常处理”以获得跟踪技术。
myMessageInspector 类实现了IDispatchMessageInspector接口。在它的BeforeSendRequest和AfterReceiveReply方法中它把消息打印到控制台。类myEndpointBehavior实现了IEndpointBehavior接口。在它的AddDispatchBehavior方法中它把myMessageInspector类添加到消息检测器列表中以便于可以被每一条消息调用。最后,主程序将myEndpointBehavior类添加到所有终结点的行为列表中。注意因为服务也有一个MEX终结点,对终结点的请求和回复也会被myEndpointBehavior打印出来。
列表5.23 在一个服务终结点行为中的消息检测器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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) { } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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()); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | [ServiceContract] public interface IStockService { [OperationContract] double GetPrice( string ticker); } public class StockService : IStockService { public double GetPrice( string ticker) { return 94.85; } } |
作者:DanielWise
出处:http://www.cnblogs.com/danielWise/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述