Welcome!

Microsoft Cloud Authors: Janakiram MSV, Yeshim Deniz, David H Deans, Andreas Grabner, Stackify Blog

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

.NET Feature — Creating Custom WCF Behaviors

Apply cross-cutting logic to your services

When building WCF services you'll eventually need to integrate common logic that may be applied across a number of services, contracts, endpoints, or operations. Examples include logging, security, error handling, and message or parameter manipulation. Since this kind of logic cuts across all of these concerns and must often be executed somewhere between the submission of a message from a client to the service, we are presented with an interesting design and programming challenge. Fortunately, WCF provides a feature called Custom Behaviors that lets us inject common and "cross-cutting" logic into the WCF runtime either at the proxy (i.e., the client) or dispatcher (i.e., the service) to achieve such ends.

The WCF Architecture for Extensibility
The WCF architecture is amazingly extensible. Figure 1 provides an overview that we can use to orient ourselves before delving into how the WCF runtime can be extended.

I'll assume that you're familiar with how to write WCF services and consume them from the client, so I won't address the client or service code. The channel stacks are where messages are prepared for transmission across the selected transport on both the client and service sides; this is the layer where your WCF bindings are applied. The middle layer in Figure 1 may be referred to as the Service Model Layer. It's responsible for sending and receiving messages to or from the channels, and invoking the appropriate methods in the client and service side code. This is where custom behaviors can be injected, and is the layer that I'll focus on in this article.

When working with custom behaviors you'll have to become familiar with a set of interface classes in two namespaces. The System.Model.Dispatcher namespace provides interfaces that you can implement on your own custom classes to write "interception logic"; these are the classes where you'll code your common logic. I refer to these as being interceptors because when they're loaded they'll intercept the normal flow of execution on either the proxy or dispatcher side to invoke your custom logic at pre-designated times. Figure 2 illustrates the sequence in which classes that implement these interfaces will be called on in the proxy and dispatcher pipelines, and Table 1 lists a few sample scenarios where you might want to use these interfaces.

The second namespace you'll need to become aware of is System.ServiceModel.Description. This namespace includes interfaces that, when implemented on your custom classes, assist in the loading of interceptors into various collections so their logic can be executed as part of the WCF runtime. Classes that implement these interfaces must be added into Behaviors collections prior to opening either the ServiceHost on the service side or the ChannelFactory on the client side. These collections are found in an in-memory representation of the entire service known as the Description Tree. The ServiceDescription class, pictured as the root of the hierarchy in Figure 3, provides access to this tree and is constructed at runtime on the dispatcher side. The same structure is available on the proxy side; the key difference is that the tree created there starts with the ServiceEndpoint class.

In Figure 3 you can infer that the interceptors (see Table 1) loaded by behaviors are applicable across several scopes. If, for example, we add a class that implements IServiceBehavior at the ServiceDescription level then the interceptors added via that behavior might apply to the service and all of its endpoints, contracts, and operations. If we add an IEndpointBehavior to a ServiceEndpoint then the interception logic injected by that behavior could apply not only to the endpoint, but also to its contracts and their operations. When IContractBehaviors are added to a ContractDescription then interception may occur for that contract and its operations. Finally, individual operations can be targeted for interception when IOperationBehaviors are added at the OperationDescription level.

One generally has three options to choose from when considering how to add behaviors to the description tree. You may add these behaviors programmatically before executing ServiceHost.Open or ChannelFactory.Open, you may use attributes, or you may opt to use configuration files. This article focuses on the last two approaches. Table 2 summarizes how classes that implement these interfaces can be added to the description tree, and it also shows where these interfaces can be applied.

If you choose to use attributes or configuration files to add behavior classes to the description tree, then the WCF runtime will detect these directives just before the ServiceHost or ChannelFactory is actually opened, and will load the corresponding classes into either the dispatcher or proxy trees respectively.

At this point you may be wondering when you should choose to add a behavior through configuration files, attributes, or programmatic means. Here are a few rules-of-thumb I would suggest. You might choose configuration files when the interceptors to be added are optional and you want the flexibility to add or remove them after the service or corresponding proxies have been deployed. Attributes should be used when you want to inject an interceptor. These types of interceptors might be required logic that should never be removed after deployment. Lastly, you might consider adding behaviors and their corresponding interceptors programmatically when you need to optionally load them depending on some conditional logic that is evaluated at runtime.

Now that we've covered the key architectural aspects of WCF that allow for the injection of interception logic through custom behaviors, let's dig into some code.

How To Log Messages Received at the Service
In this section I'll show you how to use a Message Inspector (IDispatchMessageInspector) and a configured Service Behavior (IServiceBehavior) to create a common "cross-cutting" behavior that logs messages. The service in this example is hosted in IIS, so you won't see any calls to ServiceHost. Additionally, while we could implement these interfaces on separate classes, I've chosen to implement both the interceptor and behavior interfaces on the same class. Such an approach may or may not make sense for your particular needs. You may, for example, want to implement interceptors in separate classes so your behavior class can load more than one interceptor.

Before I go any further I should also point out that the following example is primarily intended to hint at the possibilities for using message inspectors. Regarding the specific need to log messages, we could also use the WCF trace facility enabled via the MessageLoggingElement class in the System.ServiceModel.Configuration namespace. With that approach, you can alter a configuration setting in your Web or app config file and view the logged messages via the ServiceTraceViewer.exe tool. The following approach essentially captures the same information, but would give you more control over how the intercepted request message might be handled. For example, you could choose to send all outputs from a Web farm to one central location. Now that I've gotten that out of the way, let's look at some code.

In Listing 1 you'll see a partial listing for a class named InsertLogging that inherits from BehaviorExtensionElement. This class also implements the IDispatchMessageInspector and IServiceBehavior interfaces.

The most appropriate interception interface to use when you need to modify, capture, or inspect messages on the service side is IDispatchMessageInspector. With this interface we can add our common logic into the AfterReceiveRequest and BeforeSendReply methods. The former is used to intercept messages and process them after they've been received from the channel and before they're sent on to the service code. The latter is used to process reply messages prior to sending them back to the clients. In Listing 1 you can see that I'm using Microsoft's Enterprise Library Logging Application Block to write the entire request message to some location. You can configure the Logging Block to write such entries to the event log, a database, a message queue, a text file, or other locations. Let's move on to see how this interception logic is loaded.

Listing 2 shows how the IServiceBehavior interface is implemented on the InsertLogging class. Here you can see that the only method into which I have added code is ApplyDispatchBehavior; the remaining two methods, Validate and AddBindingParameters, aren't relevant to this topic.

In Listing 2 you'll see that I iterate through each of the ChannelDispatchers associated with the ServiceHost, and then loop through all of the EndpointDispatchers that are found on each ChannelDispatcher. From this you can surmise that a service has one or many channel dispatchers, and each channel dispatcher could have one or many endpoint dispatchers. Since I want to intercept all messages flowing into each and every operation that a service exposes on each of its endpoints, I can add a reference to my interceptor at this point. You can see that after a reference to an EndpointDispatcher is acquired, a reference to the IDispatchMessageInspector class (i.e., the InsertLogging class) is added to endpoint dispatcher's MessageInspectors collection.

More Stories By Rob Daigneau

Rob Daigneau is the Director of Architecture for Monster.com, one of the most visited web sites in the world. Rob has over 18 years of experience designing and implementing enterprise-class applications for a broad array of industries from manufacturing, to financial services, to retail. He is also a frequent speaker at conferences such as VS Live! and DevTeach, and writes on a number of industry-related topics for .NET Developer's Journal as well as at www.DesignPatternsFor.Net

Comments (2) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
John Fitzpatrick 05/14/08 02:56:29 PM EDT

Great article. The step by step description was really helpful and made this complicated topic digestible.
Thanks

Sachin 11/13/07 10:41:34 PM EST

Hi,

I saw this article and i am very impressed by this message logging idea. If you can send me the sample code for the given article then i will try to inject the policy injection for tracing and exception handling in the WCF services using Application Block.

Regards,

Sachin

@ThingsExpo Stories
With major technology companies and startups seriously embracing Cloud strategies, now is the perfect time to attend 21st Cloud Expo October 31 - November 2, 2017, at the Santa Clara Convention Center, CA, and June 12-14, 2018, at the Javits Center in New York City, NY, and learn what is going on, contribute to the discussions, and ensure that your enterprise is on the right path to Digital Transformation.
SYS-CON Events announced today that N3N will exhibit at SYS-CON's @ThingsExpo, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. N3N’s solutions increase the effectiveness of operations and control centers, increase the value of IoT investments, and facilitate real-time operational decision making. N3N enables operations teams with a four dimensional digital “big board” that consolidates real-time live video feeds alongside IoT sensor data a...
Amazon is pursuing new markets and disrupting industries at an incredible pace. Almost every industry seems to be in its crosshairs. Companies and industries that once thought they were safe are now worried about being “Amazoned.”. The new watch word should be “Be afraid. Be very afraid.” In his session 21st Cloud Expo, Chris Kocher, a co-founder of Grey Heron, will address questions such as: What new areas is Amazon disrupting? How are they doing this? Where are they likely to go? What are th...
In his Opening Keynote at 21st Cloud Expo, John Considine, General Manager of IBM Cloud Infrastructure, will lead you through the exciting evolution of the cloud. He'll look at this major disruption from the perspective of technology, business models, and what this means for enterprises of all sizes. John Considine is General Manager of Cloud Infrastructure Services at IBM. In that role he is responsible for leading IBM’s public cloud infrastructure including strategy, development, and offering ...
Digital transformation is changing the face of business. The IDC predicts that enterprises will commit to a massive new scale of digital transformation, to stake out leadership positions in the "digital transformation economy." Accordingly, attendees at the upcoming Cloud Expo | @ThingsExpo at the Santa Clara Convention Center in Santa Clara, CA, Oct 31-Nov 2, will find fresh new content in a new track called Enterprise Cloud & Digital Transformation.
SYS-CON Events announced today that NetApp has been named “Bronze Sponsor” of SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. NetApp is the data authority for hybrid cloud. NetApp provides a full range of hybrid cloud data services that simplify management of applications and data across cloud and on-premises environments to accelerate digital transformation. Together with their partners, NetApp emp...
Smart cities have the potential to change our lives at so many levels for citizens: less pollution, reduced parking obstacles, better health, education and more energy savings. Real-time data streaming and the Internet of Things (IoT) possess the power to turn this vision into a reality. However, most organizations today are building their data infrastructure to focus solely on addressing immediate business needs vs. a platform capable of quickly adapting emerging technologies to address future ...
Most technology leaders, contemporary and from the hardware era, are reshaping their businesses to do software. They hope to capture value from emerging technologies such as IoT, SDN, and AI. Ultimately, irrespective of the vertical, it is about deriving value from independent software applications participating in an ecosystem as one comprehensive solution. In his session at @ThingsExpo, Kausik Sridhar, founder and CTO of Pulzze Systems, will discuss how given the magnitude of today's applicati...
As popularity of the smart home is growing and continues to go mainstream, technological factors play a greater role. The IoT protocol houses the interoperability battery consumption, security, and configuration of a smart home device, and it can be difficult for companies to choose the right kind for their product. For both DIY and professionally installed smart homes, developers need to consider each of these elements for their product to be successful in the market and current smart homes.
SYS-CON Events announced today that Avere Systems, a leading provider of enterprise storage for the hybrid cloud, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere delivers a more modern architectural approach to storage that doesn't require the overprovisioning of storage capacity to achieve performance, overspending on expensive storage media for inactive data or the overbui...
Widespread fragmentation is stalling the growth of the IIoT and making it difficult for partners to work together. The number of software platforms, apps, hardware and connectivity standards is creating paralysis among businesses that are afraid of being locked into a solution. EdgeX Foundry is unifying the community around a common IoT edge framework and an ecosystem of interoperable components.
SYS-CON Events announced today that Avere Systems, a leading provider of hybrid cloud enablement solutions, will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Avere Systems was created by file systems experts determined to reinvent storage by changing the way enterprises thought about and bought storage resources. With decades of experience behind the company’s founders, Avere got its ...
High-velocity engineering teams are applying not only continuous delivery processes, but also lessons in experimentation from established leaders like Amazon, Netflix, and Facebook. These companies have made experimentation a foundation for their release processes, allowing them to try out major feature releases and redesigns within smaller groups before making them broadly available. In his session at 21st Cloud Expo, Brian Lucas, Senior Staff Engineer at Optimizely, will discuss how by using...
In this strange new world where more and more power is drawn from business technology, companies are effectively straddling two paths on the road to innovation and transformation into digital enterprises. The first path is the heritage trail – with “legacy” technology forming the background. Here, extant technologies are transformed by core IT teams to provide more API-driven approaches. Legacy systems can restrict companies that are transitioning into digital enterprises. To truly become a lead...
SYS-CON Events announced today that CAST Software will exhibit at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 - Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. CAST was founded more than 25 years ago to make the invisible visible. Built around the idea that even the best analytics on the market still leave blind spots for technical teams looking to deliver better software and prevent outages, CAST provides the software intelligence that matter ...
SYS-CON Events announced today that Daiya Industry will exhibit at the Japanese Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Ruby Development Inc. builds new services in short period of time and provides a continuous support of those services based on Ruby on Rails. For more information, please visit https://github.com/RubyDevInc.
As businesses evolve, they need technology that is simple to help them succeed today and flexible enough to help them build for tomorrow. Chrome is fit for the workplace of the future — providing a secure, consistent user experience across a range of devices that can be used anywhere. In her session at 21st Cloud Expo, Vidya Nagarajan, a Senior Product Manager at Google, will take a look at various options as to how ChromeOS can be leveraged to interact with people on the devices, and formats th...
SYS-CON Events announced today that Yuasa System will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Yuasa System is introducing a multi-purpose endurance testing system for flexible displays, OLED devices, flexible substrates, flat cables, and films in smartphones, wearables, automobiles, and healthcare.
SYS-CON Events announced today that Taica will exhibit at the Japan External Trade Organization (JETRO) Pavilion at SYS-CON's 21st International Cloud Expo®, which will take place on Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA. Taica manufacturers Alpha-GEL brand silicone components and materials, which maintain outstanding performance over a wide temperature range -40C to +200C. For more information, visit http://www.taica.co.jp/english/.
Enterprises have taken advantage of IoT to achieve important revenue and cost advantages. What is less apparent is how incumbent enterprises operating at scale have, following success with IoT, built analytic, operations management and software development capabilities – ranging from autonomous vehicles to manageable robotics installations. They have embraced these capabilities as if they were Silicon Valley startups. As a result, many firms employ new business models that place enormous impor...