2010-11-10 46 views
13

我已經實現了自定義IParameterInspector,我希望它對我服務上的每個操作都能執行。WCF與服務上的所有操作相同的IParameterInspector

我的理解是,IParameterInspector的實現只能用於IOperationBehavior的實現,而實體IOperationBehavior的實現只能用於使用屬性修飾單個操作。

是否有人知道我是否可以在服務級別註冊我的IParameterInspector,以便它可以執行服務中的所有操作?

回答

14

感謝this及其後this,我找到了我在找的東西。

IParameterInspector不需要在IOperationBehavior級別。他們可以在IServiceBehavior級別。在服務級別ApplyDispatchBehavior方法中,您需要遍歷所有操作並分配檢查器行爲。

我在滿級...

[AttributeUsage(AttributeTargets.Class)] 
public class ServiceLevelParameterInspectorAttribute : Attribute, IParameterInspector, IServiceBehavior 
{ 
    public object BeforeCall(string operationName, object[] inputs) 
    { 
     // Inspect the parameters. 
     return null; 
    } 

    public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState) 
    { 
    } 

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

    public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters) 
    { 
    } 

    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    { 
     foreach (ChannelDispatcher channelDispatcher in serviceHostBase.ChannelDispatchers) 
     { 
      if (channelDispatcher == null) 
      { 
       continue; 
      } 

      foreach(var endPoint in channelDispatcher.Endpoints) 
      { 
       if (endPoint == null) 
       { 
        continue; 
       } 

       foreach(var opertaion in endPoint.DispatchRuntime.Operations) 
       { 
        opertaion.ParameterInspectors.Add(this); 
       } 
      } 
     } 
    } 
} 
+2

有點老了,但爲什麼繼續在你的代碼調用? – itchi 2013-04-25 20:46:41

+1

@itchi現在更老了,但我猜測是因爲「該集合包含ChannelDispatcherBase對象(而不僅僅是ChannelDispatcher的實例),因爲它也用於希望保留Windows Communication Foundation(WCF)編程模型但替換系統提供的運行時「。看起來代碼可能會觸發無效的強制轉換異常。最好使用保持ChannelDispatcherBase並使用「as」運算符。 – trydis 2014-09-09 21:41:01