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: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds