Welcome!

Microsoft Cloud Authors: Nick Basinger, Kevin Benedict, Pat Romanski, Liz McMillan, Lori MacVittie

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

.NET Feature — Creating Custom WCF Behaviors

Apply cross-cutting logic to your services

Now that you've seen how to use an interceptor to create common logic (see Listing 1), and how to use a behavior to load that interceptor (see Listing 2), let's see how the behavior can be instructed to load via configuration files. You may first want to refer back to Listing 1 to see that the InsertLogging class inherits from the BehaviorExtensionElement class; this is the first thing you'll need to do if you want to use configured behaviors. When this is done, you must override that class's BehaviorType property and CreateBehavior method, as is shown in Listing 3.

The BehaviorType property in Listing 3 returns the type of behavior, which happens to be InsertLogging. CreateBehavior is a "creational method" that returns an instantiation of a new InsertLogging object. Altogether, this provides the configuration system the information it requires to load the behavior class at the appropriate time.

Let's move on to see what you'll need to put in your configuration files to associate a behavior with a specific service. The first part of the system.serviceModel section from web.config is presented in Listing 4.

The key thing to notice in Listing 4 is the behaviorConfiguration attribute. This tells the configuration system that a specific behavior, in this case one named LogBehavior, should be configured for use with this service. Listing 5 shows the behaviors section where you can see the actual definition for that behavior. Note that it has an element named LoggingBehavior, which indicates the "extension" to be associated with LogBehavior.

Listing 5 shows that the behaviorExtensions element contains a directive to add a custom .Net type named WCF.Behaviors.InsertLogging that can be found in the assembly named WCF.Behaviors. If you have set up your configuration file properly then the WCF runtime will acquire this information prior to opening the ServiceHost and will execute the logic found in Listing 3 and then the logic in Listing 2. If all has gone according to plan up to this point then when a message flows into any service endpoint, the common logging logic found in Listing 1 will be executed.

How To Inject Client Information into the SOAP Headers
Now let's see how we can use a client-side Message Inspector and a Contract Behavior so that we can track which applications use a given version of a contract. Let's say that we always want to enforce this behavior, so we decide to use attributes to tell the WCF runtime to always load the behavior on the client. Listing 6 shows a portion of a class named InsertClientInfo. Notice that it inherits from the Attribute class and also implements IClientMessageInspector and IContractBehavior.

In summary, the logic in Listing 6 creates a custom MessageHeader using the ClientInfo type (see Listing 9), and adds that header to the request message. This all occurs before that message is sent through the proxy's channel stack and over the wire to the service. To put this interceptor into the WCF runtime on the proxy side, we can create code in the ApplyClientBehavior method so that a reference to the InsertClientInfo class will be added into the MessageInspectors collection of the proxy's clientRuntime. This is shown in Listing 7.

Now we have to alter the client proxy code so the ApplyClientBehavior method will be invoked. To do this we can either edit the output file produced by Svcutil.exe, or if we use the Visual Studio IDE to add a service reference to a project, we can edit the .cs file that it adds. Listing 8 shows how an attribute may be added to the code for the client proxy.

In this case, I used Visual Studio to add the service reference; this is why you see information from the CodeDom. Since I want to capture client information for all calls to a given service contract, I have to know the name of either the service interface class or the class that implements this interface. Lucky for me, I happen to know that the interface is named IBargainAirService. To tell the WCF runtime that it should load a behavior, the IBargainAirService interface has been decorated with the [WCF.Behaviors.InsertClientInfo] attribute. By choosing to decorate the IBargainAirService interface with this attribute, the effect will be that all classes in the proxy that implement this interface will have this behavior applied to them. Now, whenever a client opens a channel factory out to the service, the logic in Listing 7 will be invoked, and when the client sends a message out to the endpoint that contains this contract, the code in Listing 6 will step in to intercept the call. Pretty cool, eh?

Conclusion
We've covered a lot of ground in this article, from the WCF architecture that supports extensibility, to a few code samples showing some of the possibilities. I hope that you can now see how this powerful feature may be tapped to apply cross-cutting logic to your services. Perhaps you've even caught a glimpse of the endless possibilities that lie beyond.

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)

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.


IoT & Smart Cities Stories
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also receive...
Nicolas Fierro is CEO of MIMIR Blockchain Solutions. He is a programmer, technologist, and operations dev who has worked with Ethereum and blockchain since 2014. His knowledge in blockchain dates to when he performed dev ops services to the Ethereum Foundation as one the privileged few developers to work with the original core team in Switzerland.
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
Bill Schmarzo, author of "Big Data: Understanding How Data Powers Big Business" and "Big Data MBA: Driving Business Strategies with Data Science," is responsible for setting the strategy and defining the Big Data service offerings and capabilities for EMC Global Services Big Data Practice. As the CTO for the Big Data Practice, he is responsible for working with organizations to help them identify where and how to start their big data journeys. He's written several white papers, is an avid blogge...
René Bostic is the Technical VP of the IBM Cloud Unit in North America. Enjoying her career with IBM during the modern millennial technological era, she is an expert in cloud computing, DevOps and emerging cloud technologies such as Blockchain. Her strengths and core competencies include a proven record of accomplishments in consensus building at all levels to assess, plan, and implement enterprise and cloud computing solutions. René is a member of the Society of Women Engineers (SWE) and a m...
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...
Whenever a new technology hits the high points of hype, everyone starts talking about it like it will solve all their business problems. Blockchain is one of those technologies. According to Gartner's latest report on the hype cycle of emerging technologies, blockchain has just passed the peak of their hype cycle curve. If you read the news articles about it, one would think it has taken over the technology world. No disruptive technology is without its challenges and potential impediments t...
If a machine can invent, does this mean the end of the patent system as we know it? The patent system, both in the US and Europe, allows companies to protect their inventions and helps foster innovation. However, Artificial Intelligence (AI) could be set to disrupt the patent system as we know it. This talk will examine how AI may change the patent landscape in the years to come. Furthermore, ways in which companies can best protect their AI related inventions will be examined from both a US and...
Bill Schmarzo, Tech Chair of "Big Data | Analytics" of upcoming CloudEXPO | DXWorldEXPO New York (November 12-13, 2018, New York City) today announced the outline and schedule of the track. "The track has been designed in experience/degree order," said Schmarzo. "So, that folks who attend the entire track can leave the conference with some of the skills necessary to get their work done when they get back to their offices. It actually ties back to some work that I'm doing at the University of San...