Welcome!

Microsoft Cloud Authors: Lori MacVittie, Elizabeth White, Yeshim Deniz, Serafima Al, Janakiram MSV

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
Dion Hinchcliffe is an internationally recognized digital expert, bestselling book author, frequent keynote speaker, analyst, futurist, and transformation expert based in Washington, DC. He is currently Chief Strategy Officer at the industry-leading digital strategy and online community solutions firm, 7Summits.
Digital Transformation is much more than a buzzword. The radical shift to digital mechanisms for almost every process is evident across all industries and verticals. This is often especially true in financial services, where the legacy environment is many times unable to keep up with the rapidly shifting demands of the consumer. The constant pressure to provide complete, omnichannel delivery of customer-facing solutions to meet both regulatory and customer demands is putting enormous pressure on...
IoT is at the core or many Digital Transformation initiatives with the goal of re-inventing a company's business model. We all agree that collecting relevant IoT data will result in massive amounts of data needing to be stored. However, with the rapid development of IoT devices and ongoing business model transformation, we are not able to predict the volume and growth of IoT data. And with the lack of IoT history, traditional methods of IT and infrastructure planning based on the past do not app...
"Akvelon is a software development company and we also provide consultancy services to folks who are looking to scale or accelerate their engineering roadmaps," explained Jeremiah Mothersell, Marketing Manager at Akvelon, in this SYS-CON.tv interview at 21st Cloud Expo, held Oct 31 – Nov 2, 2017, at the Santa Clara Convention Center in Santa Clara, CA.
DXWorldEXPO LLC, the producer of the world's most influential technology conferences and trade shows has announced the 22nd International CloudEXPO | DXWorldEXPO "Early Bird Registration" is now open. Register for Full Conference "Gold Pass" ▸ Here (Expo Hall ▸ Here)
More and more brands have jumped on the IoT bandwagon. We have an excess of wearables – activity trackers, smartwatches, smart glasses and sneakers, and more that track seemingly endless datapoints. However, most consumers have no idea what “IoT” means. Creating more wearables that track data shouldn't be the aim of brands; delivering meaningful, tangible relevance to their users should be. We're in a period in which the IoT pendulum is still swinging. Initially, it swung toward "smart for smart...
IoT is rapidly becoming mainstream as more and more investments are made into the platforms and technology. As this movement continues to expand and gain momentum it creates a massive wall of noise that can be difficult to sift through. Unfortunately, this inevitably makes IoT less approachable for people to get started with and can hamper efforts to integrate this key technology into your own portfolio. There are so many connected products already in place today with many hundreds more on the h...
Here are the Top 20 Twitter Influencers of the month as determined by the Kcore algorithm, in a range of current topics of interest from #IoT to #DeepLearning. To run a real-time search of a given term in our website and see the current top influencers, click on the topic name. Among the top 20 IoT influencers, ThingsEXPO ranked #14 and CloudEXPO ranked #17.
Join IBM November 1 at 21st Cloud Expo at the Santa Clara Convention Center in Santa Clara, CA, and learn how IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Cognitive analysis impacts today’s systems with unparalleled ability that were previously available only to manned, back-end operations. Thanks to cloud processing, IBM Watson can bring cognitive services and AI to intelligent, unmanned systems. Imagine a robot vacuum that becomes your personal assistant tha...
As data explodes in quantity, importance and from new sources, the need for managing and protecting data residing across physical, virtual, and cloud environments grow with it. Managing data includes protecting it, indexing and classifying it for true, long-term management, compliance and E-Discovery. Commvault can ensure this with a single pane of glass solution – whether in a private cloud, a Service Provider delivered public cloud or a hybrid cloud environment – across the heterogeneous enter...
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
DXWorldEXPO LLC announced today that ICC-USA, a computer systems integrator and server manufacturing company focused on developing products and product appliances, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. DXWordEXPO New York 2018, colocated with CloudEXPO New York 2018 will be held November 11-13, 2018, in New York City. ICC is a computer systems integrator and server manufacturing company focused on developing products and product appliances to meet a wide range of ...
Major trends and emerging technologies – from virtual reality and IoT, to Big Data and algorithms – are helping organizations innovate in the digital era. However, to create real business value, IT must think beyond the ‘what’ of digital transformation to the ‘how’ to harness emerging trends, innovation and disruption. Architecture is the key that underpins and ties all these efforts together. In the digital age, it’s important to invest in architecture, extend the enterprise footprint to the cl...
DXWorldEXPO LLC announced today that All in Mobile, a mobile app development company from Poland, will exhibit at the 22nd International CloudEXPO | DXWorldEXPO. All In Mobile is a mobile app development company from Poland. Since 2014, they maintain passion for developing mobile applications for enterprises and startups worldwide.
In an era of historic innovation fueled by unprecedented access to data and technology, the low cost and risk of entering new markets has leveled the playing field for business. Today, any ambitious innovator can easily introduce a new application or product that can reinvent business models and transform the client experience. In their Day 2 Keynote at 19th Cloud Expo, Mercer Rowe, IBM Vice President of Strategic Alliances, and Raejeanne Skillern, Intel Vice President of Data Center Group and ...
"We are a well-established player in the application life cycle management market and we also have a very strong version control product," stated Flint Brenton, CEO of CollabNet,, in this SYS-CON.tv interview at 18th Cloud Expo at the Javits Center in New York City, NY.
In his session at @ThingsExpo, Arvind Radhakrishnen discussed how IoT offers new business models in banking and financial services organizations with the capability to revolutionize products, payments, channels, business processes and asset management built on strong architectural foundation. The following topics were covered: How IoT stands to impact various business parameters including customer experience, cost and risk management within BFS organizations.
While the focus and objectives of IoT initiatives are many and diverse, they all share a few common attributes, and one of those is the network. Commonly, that network includes the Internet, over which there isn't any real control for performance and availability. Or is there? The current state of the art for Big Data analytics, as applied to network telemetry, offers new opportunities for improving and assuring operational integrity. In his session at @ThingsExpo, Jim Frey, Vice President of S...
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
Andrew Keys is Co-Founder of ConsenSys Enterprise. He comes to ConsenSys Enterprise with capital markets, technology and entrepreneurial experience. Previously, he worked for UBS investment bank in equities analysis. Later, he was responsible for the creation and distribution of life settlement products to hedge funds and investment banks. After, he co-founded a revenue cycle management company where he learned about Bitcoin and eventually Ethereal. Andrew's role at ConsenSys Enterprise is a mul...