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

  • There are no comments yet. Be the first to comment!

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

Top White Papers and Webcasts

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

  • Live Event Date: September 10, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild". This loop of continuous delivery and continuous feedback is …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds