WCF Articles

WCF Contracts

WCF Contract
WCF contracts is used to define the behavior of WCF services. These are created in code by developers and are exposed to clients in the service metadata.

There are five types of contracts :

1. Service Contract – A service contract defines the operations that a service supports and maps to a portType in Web Service Description Language (WSDL). Service contracts are implemented as interfaces that are annotated with the ServiceContract attribute.

[ServiceContract]
public interface IRailwayTicket
{ …}

2. Operation contracts define the individual operations that a service supports and map to operations in WSDL. Operations are defined by adding methods to a Service Contract interface that is annotated with the OperationContract attribute.
[OperationContract]
void BookTrainTicket();

3. Data contracts is used to define complex types. They are defined by applying the DataContract and DataMember attributes to classes.
[DataContract]
public class Ticket
{
      [DataMember]
      public int TicketNo;
}

4. Message contracts describe the entire SOAP message format. They can use data contracts and serializable types to emit schema for complex types, and they also make it possible to control the SOAP message headers and body explicitly, by using a single type. Message contracts provide a simple method to add custom SOAP headers to incoming and outgoing messages.

[MessageContract]
public class BookingRequest
{
        [MessageHeader]
        public string User;
        [MessageBody]
        public string TicketNo;
}

5. Fault Contract document the errors that WCF code is likely to produce, and WCF maps Fault objects to SOAP faults. Note that the type specified in the FaultContract does not have to be an exception, although it often will be.

[OperationContract]
[FaultContract(typeof(DivideByZeroException))]
void GetDiscount();

A Fault is generated by throwing a FaultException:

throw new FaultException(someException);

Categories: WCF Articles, WCF Tutorial

Leave a Reply