Tuesday, November 14, 2006

WCF Contracts Defined

A WCF service publishes the operations that it supports by using a service contract. This contract defines the operations that the service provides, without specifying how the operations should be implemented.

Operations are defined by adding methods to a Service Contract interface that is annotated with the OperationContract attribute. Only methods that are qualified by the OperationContract attribute are service operations, and can be exposed to clients.


[ServiceContract]
public interface IOrderService {
  [OperationContract]
  void CreateOrder(int orderNumber);
  [OperationContract]
  void AddItemToOrder(int orderNumber, Item itm);
  [OperationContract]
  Order GetOrderDetails(int orderNumber);
}


A WCF service is implemented by creating a class that implements the service interface.


public class OrderService : IOrderService {
  void CreateOrder(int orderNumber) {
    // implementation details
  }
  void AddItemToOrder(int orderNumber, Item itm) {
    // implementation details
  }
  Order GetOrderDetails(int orderNumber) {
    // implementation details
  }
}


Data contracts define how complex types are serialized when they are used in WCF service operations. They defined by applying the DataContract attribute to a class, and then adding DataMember attributes to fields and properties to show which members are to be exposed to clients.


[DataContract]
public class Order {
  [DataMember]
  public int OrderNumber;
  [DataMember]
  public String ClientName;
  ...
}


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 MyRequest {
  [MessageHeader]
  public string field1;
  [MessageBody]
  public string field2;
}


A WCF service reports errors by using Fault objects. Fault contracts 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.


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


A Fault is generated by throwing a FaultException:


throw new FaultException(someException);

No comments: