Basically a WCF Contract is an agreement between the two parties i.e. a Service and a Client. In Windows Communication Foundation, Contracts are categorized as behavioral or structural.
ServiceContract attribute is used to mark a type as Service Contract that contains operations.
OperationContract attribute is used to mark the operations that will be exposed.
FaultContract defines what errors are raised by the service being exposed.
DataContract attribute defines types that will be moved between the parties.
MessageContract attribute define the structure of the SOAP message.
In this WCF Tutorial, we will discuss and implement Contracts in Windows Communication Foundation using a step by step approach with practical examples.
Service Contract and Operation Contract
Service Contract basically describe the operations a service expose to other party( i.e. a client). We can map a WCF Service Contract to a WSDL (Web Service Description Language).
It’s recommended to apply S
erviceContract attribute to an interface, although it can be applied to a class as well. Applying it to an interface give us clear separation of contract and it’s implementation.
- what operations are exposed by the service?
- platform independent description of interface as well as methods of our service.
- MEP (Message Exchange Pattern) between the parties i.e. Request/Response, One-Way or Duplex . Please follow here for detailed description of MEPs.
In order to define a Service Contract, we will apply
ServiceContract attribute to a .NET Interface and
OperationContract attribute to methods as follows:
class SimpleService : ISimpleService
public string SimpleOperation()
return “Simple Operation Result”;
In above code, we used
ServiceContract attribute to mark
ISimpleService (an interface) as a Service Contract and
OperationContract attribute to method “
SimpleOperation“. Further provided an implementation class “
ServiceContract attribute is not inherited, means if we are defining another interface/class as a Service Contract inheriting from
ISimpleContract, we still have to explicitly mark it with
In above example, we use ServiceContract attribute without any parameter but we can pass parameters also like Name, Namespace, ConfigurationName, ProtectionLevel, SessionMode etc as follows:
[ServiceContract(Name = "MySimpleService")]
In this WCF Tutorial, we learnt about two behavioral contracts i.e. Service Contract and Operation contracts. To learn about Structural Contracts (Data Contract and Message Contract).
Other Related Articles:
The post WCF Contracts Simplified appeared first on WCF Tutorial.