This project is read-only.

WCF and Code Contracts

Topics: Web Api
Feb 6, 2011 at 10:31 PM

Combining WCF and Code Contracts:

Problem description:
Suppose we want to create a WCF service with code contracts. A straightforward approach would be as follows:

using System.ServiceModel;
using System.Diagnostics.Contract;

public interface IService {
  double squareRoot(double d);

public class IServiceImpl : IService {
  public double squareRoot(double d) {
    Contract.Requires(d >= 0);
    return Math.Sqrt(d);

This WCF service implementation can be successfully compiled and deployed. However, the generated WSDL description does not include any information about code contracts. In other words, code contracts are completely ignored and are not part of the WSDL interface.

There are two important consequences to stress here:
1) Code contracts imposed on the service implementation are not considered when generating the proxy classes.
2) Clients of the WCF service are not aware of any code contracts. Hence, code contracts support such as static analysis and runtime checking is not available on client side.

The concept (sketch)
In order to bring code contracts to the WCF consumer, the following additional activities will be performed:
- During deployment of the service, the code contracts expressions are extracted from the WCF service implementation class and are translated into corresponding WS-Policy assertions (so called code contracts assertions).
- The resulting WS-Policy description is included into the WSDL interface of the WCF service.

In order to exploit code contracts contained in WSDL on client side, we will enhance the generated proxy classes. This is achieved by two activities:
- Extraction of the code contracts expressions contained in the WSDL description.
- Creation of corresponding Contract method calls and integration into the proxy classes.

Complete description
The full concept is described in the
proceedings of the Service Computation 2010 conference (

Proof of concept
There is a running proof of concept implementation, which shows the feasibility of the approach.

Any feedback is welcome and best regards