WCF Same IParameterInspector for all operations on a service
Asked Answered
S

1

13

I have implemented a custom IParameterInspector and I want to have it execute for every single operation on my service.

My understanding is that IParameterInspector implementations can only be used with IOperationBehavior implementations, and that intern IOperationBehavior implementation can only be used to decorate individual operations using an attribute.

Does anyone know if there is a way I can register my IParameterInspector at a service level so that it can execute for all operations in the service?

Salver answered 10/11, 2010 at 11:17 Comment(0)
S
14

Thanks to this and subsequenbtly this, I found what I was looking for.

IParameterInspector does not need to be at the IOperationBehavior level. They can be at the IServiceBehavior level. In the service level ApplyDispatchBehavior method you need to loop through all its operations and assign the inspector behaviour.

My class in full...

[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);
                }
            }
        }
    }
}
Salver answered 10/11, 2010 at 11:51 Comment(1)
@itchi Even older now, but i'm guessing because "The collection contains ChannelDispatcherBase objects (and not just instances of ChannelDispatcher) because it is also used by developers who want to keep the Windows Communication Foundation (WCF) programming model but replace the system-provided runtime". Looks like the code could trigger an invalid cast exception. Would be better to use keep ChannelDispatcherBase and use the "as" operator.Leah

© 2022 - 2024 — McMap. All rights reserved.