New Features in Windows Communication Foundation (WCF) 4.0

Introduction

There have been quite a few enhancements and new features introduced in WCF 4.0. These new features and enhancements are a major boost to productivity, flexibility and they facilitate seamless development of service oriented applications. This article discusses the new features and enhancements in WCF 4.0 and how one can make use of them in applications.

What is Windows Communication Foundation (WCF)?

Windows Communication Foundation (WCF) is a platform that can be used to design and implement platform independent, scalable services. It is a framework from Microsoft that provides a platform for unification of a number of enterprise technologies under one roof. The MSDN states, "Windows Communication Foundation (WCF) is Microsoft's unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments."

Reference: http://msdn.microsoft.com/en-us/library/ms735119.aspx

WCF was introduced as part of .NET Framework 3.0 in 2006 and was initially named "Indigo". The forthcoming sections in this article presents the new features and enhancements in WCF 4.0.

Pre-requisites

To work with the concepts and the code examples presented in this article, you should have the following installed on your system: Microsoft Visual Studio 2010 RC or higher

New Features and Enhancements in WCF 4.0

The new and enhanced features in Windows Communication Foundation 4.0 include the following:

  • Support for simplified configuration
  • Support for standard endpoints
  • Support for discovery
  • Support for simplified IIS hosting
  • Enhanced support for REST
  • Support for routing service
  • Support for workflow services

We will discuss each of these new features and enhancements in the sections that follow.

Support for Simplified Configuration

Configuration in WCF 4.0 is much simpler compared to the earlier versions of WCF. WCF 4.0 provides default endpoints, binding, and behavior. Refer to the WCF 4.0 service shown below:

[ServiceContract]
public class CustomerService
{
    [OperationContract]
    public string GetCustomerName(int customerID)
    {
        //Code to search customer name based on customerID and return it.
    }
}
Here's an example of the simple configuration you would use to host the service.
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost serviceHost = new ServiceHost
                 (typeof(CustomerService));
                 serviceHost.AddServiceEndpoint (typeof(CustomerService), new BasicHttpBinding(), "http://localhost:1212/ CustomerService.svc");
            serviceHost.Open();
            Console.WriteLine("The Customer Service has been started");
            Console.ReadLine();
            serviceHost.Close();
        }
    }
To consume the service, you can use the following configuration:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled ="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
 </system.serviceModel>
</configuration>
To specify a more secure wsHttpBinding binding, you can specify the following configuration in your configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled ="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="wsHttpBinding" scheme ="http"/>
    </protocolMapping>
 </system.serviceModel>
</configuration>

Support for Standard Endpoints

WCF 4.0 provides support for standard endpoints--a set of preconfigured endpoints to minimize on the otherwise tedious configuration that is needed to host or consume a WCF service. The standard endpoints available in WCF 4.0 include the following:

  • dynamicEndPoint
  • discoveryEndpoint
  • udpDiscoveryEndpoint
  • announcementEndpoint
  • udpAnnouncementEndpoint
  • mexEndPoint
  • webHttpEndpoint
  • webScriptEndpoint
  • workflowControlEndpoint


New Features in Windows Communication Foundation (WCF) 4.0

Support for Discovery

The ability to dynamically resolve the service endpoints based on some predefined criteria is one of the most striking of all the new features and enhancements in WCF 4.0. The following code snippet is the entire code configuration you need to specify the base addresses and endpoints and other necessary configuration information for a WCF 4.0 service:

<configuration>
    <system.serviceModel>
      <services>
        <service name="CustomerService"
                 behaviorConfiguration="serviceBehavior">
          <host>
            <baseAddresses>
              <add baseAddress="http://localhost:1234/CustomerService"/>
            </baseAddresses>
          </host>
          <endpoint address=""
                    binding="basicHttpBinding"
                    contract="ICustomerService" />
          <endpoint name="udpDiscovery" kind="udpDiscoveryEndpoint"/>
        </service>
      </services>
      <behaviors>
        <serviceBehaviors>
          <behavior name="serviceBehavior">
            <serviceDiscovery />
          </behavior>
        </serviceBehaviors>        
      </behaviors>
    </system.serviceModel>
</configuration>

To consume the customer service using the discovery API at runtime from the client side, you can use this code:

DiscoveryClient discoveryClient = new DiscoveryClient("udpDiscoveryEndpoint");
FindCriteria findCriteria = new FindCriteria(typeof(ICustomerService));
FindResponse findResponse = discoveryClient.Find(findCriteria);
if (findResponse.Endpoints.Count > 0)
{
    EndpointAddress endPointAddress = findResponse.Endpoints[0].Address;
    ChannelFactory<ICustomerServiceChannel> channelFactory = new ChannelFactory<ICustomerServiceChannel>(
        new BasicHttpBinding(), endPointAddress);
    ICustomerServiceChannel serviceClient = new factory.CreateChannel();
    String customerName = client.GetCustomerName(10);    
    serviceClient.Close();
    channelFactory.Close();
}

Support for Simplified IIS Hosting

WCF 4.0 provides support for simplified configuration for hosting services in the IIS. Refer to the code listing below that illustrates a WCF 4.0 Service:

<!-- StudentService.svc -->
<%@ ServiceHost Language="C#" Debug="true" Service="StudentService
CodeBehind="~/App_Code/StudentService.cs" %>
[ServiceContract]
public class StudentService
{
    [OperationContract]
    public string GetStudentName(int studentID)
    {
        //Code to search student name based on student ID and return it.
    }
}

You can easily enable the service metadata in the application's web.config file by specifying the following:

<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
</system.serviceModel>
To eliminate the need of a .svc file, you would like to define virtual service activation endpoints for the service as shown below:
<configuration>
  <system.serviceModel>
    <serviceHostingEnvironment>
      <serviceActivations>
        <add relativeAddress="StudentService.svc" service="StudentService"/>
      </serviceActivations>
    </serviceHostingEnvironment>
  </system.serviceModel>
</configuration>

Enhanced Support for REST

Representational State Transfer (REST) is an architectural paradigm that can be used for designing and developing scalable, interoperable, platform and protocol independent services. WCF 4.0 provides seamless support for design and development of REST-based services. Note that support for REST-based services was also provided as part of the earlier version of WCF, but, now with WCF 4.0, designing, implementing and managing REST-based services has become much simpler.

You can design and implement REST-based services in WCF 4.0 using a new binding called WebHttpBinding. To make a service RESTful, you need to use the WebGet attribute as shown in the code listing below:

[ServiceContract]
public interface IStudentDataService
{
[OperationContract]
[WebGet]
int GetStudentCount(string courseCode);
}
The following code snippet illustrates how you can specify the binding information for the RESTful service:
<service name ="StudentService" behaviorConfiguration="Default">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:1212/StudentService"/>
          </baseAddresses>
        </host>
        <endpoint
          address=""
          binding ="webHttpBinding"
          contract="IStudentService" />
</service>

In WCF 4.0, you can configure an automatic help page that describes the REST-based services. To do this, here's all you need to specify in your application's configuration file:

<configuration>
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <behaviors>
      <endpointBehaviors>
        <behavior name="TestHelpBehavior">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="TestWCFService">
        <endpoint behaviorConfiguration="TestHelpBehavior"
                  binding="webHttpBinding"
                  contract="TestWCFService" />
      </service>
    </services>
  </system.serviceModel>
</configuration>

Support for Routing Service

WCF 4.0 provides support for routing through the usage of the RoutingService class. Hosting a routing service is similar to hosting a WCF service. Routing Service provides versioning, protocol bridging, transaction, error handling support. Here's what the RoutingService class looks like:

[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any,
    InstanceContextMode = InstanceContextMode.PerSession,
    UseSynchronizationContext = false, ValidateMustUnderstand = false)]
public sealed class RoutingService : ISimplexDatagramRouter, ISimplexSessionRouter,
    IRequestReplyRouter, IDuplexSessionRouter
{
    //Class members
}

Support for Workflow Services

WCF 4.0 provides support for integrating WCF and WF to implement declarative long running workflow services seamlessly. In the earlier version of .NET Framework, i.e., .NET Framework 3.5, you were restricted to using workflow services to asynchronous long running processes only. In .NET 4.0, the performance for the workflow services have been improved to a considerable extent and you can now use WCF and WF in conjunction to design and implement declarative high performant services with ease. In WF 4.0, you have powerful messaging capabilities to achieve close integration with WCF 4.0. Also, .NET Framework 4.0 provides a much improved infrastructure for hosting workflow services in IIS.

The following code snippet illustrates how you can configure a workflow service:

<configuration>
  <system.serviceModel>
    <services>
      <service name="TestWorkflowService">
        <endpoint binding="basicHttpContextBinding" contract="ITestWorkflowService"/>
      </service>
</services>
</system.serviceModel>
</configuration>

References: http://msdn.microsoft.com/en-us/library/ee354381.aspx

Summary

WCF 4.0 has eliminated the pain of specifying tedious configuration details to host WCF services. With enhancements to configuration, tracing, serialization, message queuing, service discovery, routing, and workflow services, WCF 4.0 promises to be the technology of choice for building scalable, service oriented, REST-based services. In this article we have had a look at the new features and enhancements in WCF 4.0 and how they can be used in applications.

Related Articles





About the Author

Joydip Kanjilal

Microsoft Most Valuable Professional, Author and Speaker. Featured in "MSDN Featured Developer of the Fortnight (India)" a number of times. Winner of Community Credit Awards at www.community-credit.com several times. Authored numerous books and articles in Microsoft .NET and its related technologies. Authored the following books:-- ASP.NET 4.0 Programming (Mc-Graw Hill Publishing) Entity Framework Tutorial (Packt Publishing) Pro Sync Framework (APRESS) Sams Teach Yourself ASP.NET Ajax in 24 Hours (Sams Publishing) ASP.NET Data Presentation Controls Essentials (Packt Publishing)

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

  • On-demand Event Event Date: September 10, 2014 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 how the best mobile …

  • On-demand Event Event Date: September 17, 2014 Another day, another end-of-support deadline. You've heard enough about the hazards of not migrating to Windows Server 2008 or 2012. What you may not know is that there's plenty in it for you and your business, like increased automation and performance, time-saving technical features, and a lower total cost of ownership. Check out this webcast and join Rich Holmes, Pomeroy's practice director of virtualization, as he discusses the future state of your servers, …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds