2011-09-28 69 views
2

我可以使用行爲來附加IParameterInspector到ClientRuntime中的每個操作,也可以附加到服務端DispatchRuntime中的每個操作。但似乎這隻能從客戶端到服務。如何在Callback方向上擴展WCF?

我也希望能夠在服務回調中附加一個IParameterInspector到客戶端,如上所示,但是我找不到任何可擴展點來做到這一點。

任何想法?

回答

3

這是一個有點模糊,似乎並沒有很好的記錄,但你可以使用標準的WCF行爲功能定製兩端。

在客戶端上,該屬性會使其發生。

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

    public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) 
    { 
     foreach (var item in clientRuntime.CallbackDispatchRuntime.Operations) 
     { 
      item.ParameterInspectors.Add(ParameterInspector.Instance); 
     } 
    } 

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) 
    { 
    } 

    public void Validate(ServiceEndpoint endpoint) 
    { 
    } 
} 

只需將此屬性應用於實現您的回調接口的類。

在服務器上,它有點棘手。您需要通過ApplyDispatchBehavior進行連接。在這種情況下,我通過服務行爲完成了它,但主體也適用於OperationBehaviors和EndpointBehaviors。

public class InspectorBehaviorAttribute : Attribute, IServiceBehavior 
{ 
    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) 
    { 
    } 

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    { 
     foreach (var item in serviceHostBase.ChannelDispatchers.OfType<ChannelDispatcher>()) 
     { 
      foreach (var ep in item.Endpoints) 
      { 
       foreach (var op in ep.DispatchRuntime.CallbackClientRuntime.Operations) 
       { 
        op.ParameterInspectors.Add(ParameterInspector.Instance); 
       } 
      } 
     } 
    } 

    public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    { 
    } 
} 

再次,只需將此屬性應用於您的服務實現,讓您的參數檢查器用於所有回調操作。

儘管這些示例演示了連接IParameterInspector實現,但對於所有其他WCF擴展點的相同方法可用於在客戶端和服務器上自定義回調通道。

+0

謝謝你,CallbackDispatchRuntime和CallbackClientRuntime是我之前的,非常感謝。 –