Service Contracts in WCF

A service contract defines the operations, or methods, that are available on the service endpoint and is exposed to the outside world. It also defines the basic message exchange patterns, such as whether the message behaves in a request/reply, one-way, or duplex behavior.
A service contract exposes specific information to the client, which enables the client to understand what the service has to offer. This information includes the following:

  • The data types in the message
  • The locations of the operations
  • The protocol information and serialization format to ensure the proper and successful communication
  • Operation grouping
  • Message exchange pattern (MEPs)

A service contract is defined by simply applying the [ServiceContract] annotation to an interface or class. The following example shows how to define an interface as a service contract:

[ServiceContract]
public interface IBookOrder
{
    //do some stuff
}

Service operations are specified by applying the [OperationContract] annotation on the methods of an interface, as illustrated in this example:

[OperationContract]
bool PlaceOrder(string orderdate, string bookisbn);
[OperationContract]
bool CheckOrder(int ordernumber);

Put these two together to make a complete service contract, as shown here:

[ServiceContract]
public interface IBookOrder
{
    [OperationContract]
    bool PlaceOrder(string orderdate, string bookisbn);
    [OperationContract]
    bool CheckOrder(int ordernumber);
}

Once the interface for the service is defined, the defined interface can then be implemented. The following example implements the IBookOrder interface defined in the preceding code:

public class BookOrder : IBookOrder
{
    Public bool PlaceOrder(string orderdate, string bookisbn)
    {
        //do something
    }
    public bool CheckOrder(int ordernumber)
    {
        //do something
    }
}

You can combine these two steps into a single implementation, as follows:

[ServiceContract]
public class BookOrder: IBookOrder
{
    [OperationContract]
    Public bool PlaceOrder(string orderdate, string bookisbn)
    {
        //do something
    }
    [OperationContract]
    public bool CheckOrder(int ordernumber)
    {
        //do something
    }
}

For a review on why you would want to do one way over the other, go back and read the post named “WCF Programming Methods.
Up until now you have been using these attributes the way they are illustrated in the preceding example. What is meant by this is that attributes (such as [ServiceContract]) are applied without parameters. However, both the [ServiceContract] and the [OperationAttribute] attributes have many parameters that can be used to specify special details pertaining to each attribute. Functions would be of little value if parameters could not be employed; the same holds true for attributes.

Tagged . Bookmark the permalink.

Leave a Reply