Best Practices for WCF Programming – Part 1

WCF (Windows Communication Foundation) provides a framework, which greatly simplifies the communication needs for any application especially for enterprise level applications. It provides an abstraction level over various protocols such as SOAP, REST etc. WCF is widely used to leverage the benefits of SOA (Service Oriented Architecture).

In this blog post, I would like to highlight few of the best practices you can follow while programming WCF (on client as well as on Server side). This blog post is first in the series of “best practices for WCF programming”. This post will be focused towards client side practices.

Here are few best practices you can follow.

1. Use Async programming pattern: As you are making call to WCF services over a channel, its always a best practice to follow async pattern.If you are calling wcf services from an UI application, then async programming can help you to have responsive UI. Otherwise, you UI thread will be held till the execution of the WCF service.

Example 1

If you are using .NET Framework 3.5+, you can use Async version of your WCF webservice. All you have to do to attach a callback to the Completed event and then invoke the async version of WCF service

 var channel = new WCFServiceClient("ClientSideBindingName"); //Create a channel using WCF service client
 channel.MyWCFServiceCompleted += channel_MyWCFServiceCompleted; // Attach the callback to completed event
 channel.MyWCFServiceAsync(); // Invoke the Async version
 void channel_MyWCFServiceCompleted(object sender, MyWCFServiceCompletedEventArgs e) //Completed CallBack
        {
           //Use e.Result to get the result
        }

Example 2

If you are using .NET framework 4.5+, there is even easier way to have async pattern in your code. You can go to my earlier blog post “Asynchronous WCF service invoke with C# 5.0 Async And Await”

for more details.

2. Exception Handling :  As per Murphy’s law “It something can go wrong it will”, its always a good practice to have exception handling mechanism built into your codes. In WCF perspective, you should have exception handlers for at least following three types of exceptions

  • FaultException ( to catch exceptions related to your business logics)
  • CommunicationException (to catch exceptions related to underlying communication stack)
  • TimeOutException (to catch the timeout of your wcf invocation)

In the catch section, after performing necessary fallback work, you can abort the channel by using channel.Abort() method. Abort method is available on IClientChannel interface. So, if you are using a channel factory approach to create the channel, you will have to cast the channel to abort the connection such as

((IClientChannel)channel).Abort();

However,If you are using ServiceClient or ChannelFactory<T> where T also implements IClientChannel, then you can directly apply the Abort method to tear down the underlying communication channel such as

channel.Abort();

3. Reuse Service Contract Assemblies : In a larger program, if you are generating the client side code and configuration to consume WCF service using SVCUtil.exe (either through console or Add Service Reference method), a duplicate code of service contract will be generated in the client application too. For a larger application, you might not like this situation. Moreover, if there are certain dependencies (Such as constructor injection etc.) then you would be requiring the assemblies of service contract (or even implementation).

So, its a good practice to share the service contract assembly to the client application and then reuse those assemblies while generating artifacts from SVCUtil. This will help in avoiding the code generation for service side contractual information.

If you are using command line utility of SVCUtil then you can use /reference switch to re-use the shared service contract assembly. However, if you are using “Add Service Reference” GUI method , then under Advanced section you can put the check mark on “Reuse types in referenced assemblies”. You can even select specified referenced assemblies if you want.

4. Use MetadataResolver for dynamic applications:

Typically, we use SVCUtil (console or GUI) to generate endpoint configurations, which we can use later to create channels. However, if you are building a dynamic applications, and you want to create dynamic channel then you need to get endpoints through program. Using MetadataResolver.Resolve static method, you can get the list of endpoint exposed by a WCF service. For this you would just need the mex endpoint address (which implements IMetadataExchange interface). Then the MetadataResolver.Resolve will use the mex endpoint address and will return a collection of service endpoints. Then you can select the required service endpoint as per your requirement (based on address, binding or contract).  And using the selected endpoint you can create your channel.

Example :

 var endpoints = MetadataResolver.Resolve(typeof (IWCFService),
                                     new EndpointAddress("mex end point address"));//provide mex end point address
 var selectedEndPoint = endpoints.First(e => e.Binding.GetType() == typeof(BasicHttpBinding)); //sample query on list of service endpoints
 var factory = new ChannelFactory<IWCFService>(selectedEndPoint); //create channel based on selected endpoint
 IWCFService channel = factory.CreateChannel(); //create channel

Here in this blog post, I have mentioned only few of the best practices, stay tuned for subsequent posts.

About these ads

Abhishek is a software architect, developer and Pluralsight author. He is very passionate about working with data especially in the field of machine learning. He has authored several courses on machine learning which are available on Pluralsight. He has been involved in several software development projects, which involves various machine learning techniques. His work focuses on architecting and developing applications especially in the area of monitoring, optimization, pattern recognition, and fault detection. His professional interests include software design patterns, agile practices, and various technologies such as WCF, WF, WPF, Silverlight, SQL Server, Entity Framework and ASP.NET MVC. He is also a Microsoft Certified Professional (HTML5, Javascript, CSS3).

Posted in Technical, WCF
2 comments on “Best Practices for WCF Programming – Part 1
  1. Hi,
    what is the best pratice for maintaining web services. Actually I dont start coding a wcf project, i start by writing a wsdl file, and then from the wsdl i generate interface code and service implementations for the wcf projet (on server side). If a client would like to consume the web service, he should get the wsdl file from the server, and generate the client code for calling the web service. Next time i maintain the web service, per example i add a new method HelloWorld2 on my wcf project(server side), i will only need to change the wsdl again, generate interface code, and write the implementation for the HelloWorld2 method.
    I am asking is it a good practice? I think it is because if you have a new version of wsdl, this way, the client will support the old wsdl and also the new wsdl file which contains the new method HelloWorld2.
    thanks you very much for your advice

    • Hi,
      First of all I want to tell any software practices mentioned anywhere are some standard practices. But you can always tweak them to suit your requirement.
      talking about your case, if following this path decreases the maintainability issues for you, then you must follow it.You need to ensure the minimum rippling effect.
      However, there are few questions I would like to ask to give your better suggestions :
      1. Does the contracts of the existing methods change over the period ?
      2. Does the older user is not supposed to update the wsdl and client code ?
      Moreover, if you can supply some pseudo code implementation, it would be better.

      With these information, I would be in better position to guide you further.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

About Me


Software Architect, Developer & Pluralsight Author

Software Architect, Developer & Pluralsight Author, Twitter Handle :

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 71 other followers

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my current or previous employer's view in anyway.
Live Feed
Follow

Get every new post delivered to your Inbox.

Join 71 other followers

%d bloggers like this: