技术开发 频道

聚焦WCF行为的扩展

  至于对Dispatch的消息检查,则可以通过IServiceBehavior,IEndpointBehavior或 IContractBehavior中DispatchRuntime的MessageInspectors添加;而对Client的消息检查则可以通过 IEndpointBehavior或IContractBehavior中ClientRuntime的MessageInspectors添加(注意,此时与IServiceBehavior无关,因为它不会作用于客户端代理)。例如:

public class PrintMessageInspectorBehavior : IDispatchMessageInspector,IEndpointBehavior
    {
        
//略去IDispatchMessageInspector接口成员的实现;

        
#region IEndpointBehavior Members
        
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
            
//empty;
        }
        
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
              clientRuntime.MessageInspectors.Add(
this);
        }
        
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
this);
        }
        
public void Validate(ServiceEndpoint endpoint)
        {
            
//empty;
        }
        
#endregion
    }

  如果实现的是IServiceBehavior接口,则需要遍历ApplyDispatchBehavior()方法中的ServiceHostBase对象:

public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            
foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers)
            {
                
foreach (EndpointDispatcher endpointDispatcher in channelDispatcher .Endpoints)
                {
                    endpointDispatcher.DispatchRuntime.MessageInspectors.Add(
this);
                }
            }
        }

  注:IDispatchMessageInspector 接口的方法为BeforeSendReply()和AfterReceiveRequest();而IClientMessageInspector接口 的方法则为BeforeSendRequest()和AfterReceiveReply()。

0
相关文章