Basically a WCF Contract is an agreement between the two parties, in other words a Service and a Client. In Windows Communication Foundation, contracts can be categorized as behavioral or structural.

Behavioral Contracts

Structural Contracts

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

A Service Contract basically describes the operations a service exposes to another party (in other words a client). We can map a WCF Service Contract to a Web Service Description Language (WSDL).
It's recommended to apply the ServiceContract attribute to an interface, although it can be applied to a class as well. Applying it to an interface provides us a clear separation of contract and its implementation.
Service Contract
It describes:
To define a Service Contract, we will apply the ServiceContract attribute to a .NET Interface and OperationContract attribute to methods as follows:
  1. [ServiceContract]
  2. interface ISimpleService
  3. {
  4. [OperationContract]
  5. string SimpleOperation();
  6. }
  7. class SimpleService : ISimpleService
  8. {
  9. public string SimpleOperation()
  10. {
  11. return "Simple Operation Result";
  12. }
  13. }
In the code above, we used the ServiceContract attribute to mark ISimpleService (an interface) as a Service Contract and the OperationContract attribute to the method "SimpleOperation". Also provided an implementation class "SimpleService".
Note: The ServiceContract attribute is not inherited, in other words if we are defining another interface/class as a Service Contract inheriting from ISimpleContract, we still need to explicitly mark it with the ServiceContract attribute.
In the preceding example, we use a ServiceContract attribute without any parameter but we can pass parameters also like Name, Namespace, ConfigurationName, ProtectionLevel, SessionMode and so on as follows:
  1. [ServiceContract(Name = "MySimpleService")]
  2. interface ISimpleService
  3. {
  4. [OperationContract]
  5. string SimpleOperation();
  6. }