Learn to Create Interceptors in WCF Services

Windows Communication Foundation (WCF) is a distributed system technology, which can be customized to any level as far as I have seen. A WCF application can be customized right from the protocols it uses until the size of the message. Also it allows you to host the service on multiple end points, each using a different binding. For example a service can be exposed through HTTP as well as TCP. In this article I will cover another useful extensibility feature that can be used to intercept the WCF request during pre or post method invocation.

Interceptors with Client and Dispatch Runtimes

In WCF there are two main components called the Client and Dispatch runtimes. The client runtime does the job of converting the method calls into messages, which will be transported to a WCF service and the dispatch runtime is the one that converts the incoming message to a method call and invokes the specific WCF operation. Both of these runtimes expose a few stages, which can be extended to perform a custom operation.

An interceptor is a component, which can be plugged into any of the stages of client or dispatch runtimes. Below are a few interceptors.

1. Parameter Inspector – To inspect or modify parameter values.
2. Message Inspector – To inspect or modify the message itself.
3. Message Formatter – To format the message based on the needs.
4. Operation Selector – To select a particular operation to be invoked.

In this article I will show you how to implement a parameter inspector and add it to a behavior in order to get the parameter inspector to become a part of the Dispatch Runtime flow.

Creating Parameter Inspector

Add a new class to the WCF service, name it ParameterValidator and implement the interface IParameterInspector, which lies under the namespace System.ServiceModel.Dispatcher. In the BeforeCall method write the code to perform the parameter validation.  The reason for choosing the BeforeCall method is that the parameter validation has to be done before the operation is invoked. Below is the code.

namespace ParameterInspectionSample
{
    public class ParameterValidator : IParameterInspector
    {
        #region IParameterInspector Members
 
        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
        {
        }
 
        public object BeforeCall(string operationName, object[] inputs)
        {
            if (Convert.ToDateTime(inputs[0]) <= DateTime.Now)
                throw new FaultException("Data should be in future!");
            if (Convert.ToString(inputs[1]).Length > 50)
                throw new FaultException("Name should be less than 50 characters!");
 
            return null;
        }
 
        #endregion
    }
}
 

Implementing a Custom Behavior

In order to place the interceptor to use we need to create a custom behavior and apply the interceptor to it. In our case we need to create a Custom Operation behavior as the data validation holds good only for a particular operation contract. Create a class named CustomDataOperationBehavior, inherit for the class Attribute and also implement the interface IOperationBehavior. In the ApplyDispatchBehavior method create the instance of the ParameterValidator class and add it to the dispatchOperation.

namespace ParameterInspectionSample
{
    public class CustomDataOperationBehavior : Attribute, IOperationBehavior
    {
        #region IOperationBehavior Members
 
        public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }
 
        public void ApplyClientBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.ClientOperation clientOperation)
        {
        }
 
        public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)
        {
            dispatchOperation.ParameterInspectors.Add(new ParameterValidator());
        }
 
        public void Validate(OperationDescription operationDescription)
        {
        }
 
        #endregion
    }
}
 

I have created this as an attribute so that the respective operation contract can be decorated with this class as shown below.

namespace ParameterInspectionSample
{
    [ServiceContract]
    public interface IService1
    {
        [CustomDataOperationBehavior]
        [OperationContract]
        string ProcessData(DateTime renewalDate, string name);
    }
}

I will leave it to the readers to explore the other inspectors. I hope this article was informative about the WCF extensibility.

Happy reading!



Related Articles

Comments

  • WCF Parameter inspector

    Posted by Nithiya on 08/12/2014 12:24am

    Very nice post. Do post for other inspectors also.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

RSS Feeds