How to: Create a Windows Communication Foundation Contract with a Class

The preferred way of creating a Windows Communication Foundation (WCF) contract is by using an interface. For more information, see How to: Define a Service Contract. An alternative, outlined here, is to create a class and then apply the ServiceContractAttribute attribute to the class directly and the OperationContractAttribute attribute to each of the methods in the class that are part of the contract.

Warning

[ServiceContract] and [ServiceContractAttribute] do the same thing. The same thing is true for [OperationContract] and [OperationContractAttribute]. In each case, the former is shorthand for the latter.

For more information about service contracts, see Designing Service Contracts.

Creating a Windows Communication Foundation contract with a class

  1. Create a new class using Visual Basic, C#, or any other common language runtime language.

  2. Apply the ServiceContractAttribute class to the class.

  3. Create methods in the class.

  4. Apply the OperationContractAttribute class to each method that must be exposed as part of the public WCF contract.

Example

The following code example shows a class that defines a service contract.

[ServiceContract]
public class CalculatorService
{
  [OperationContract]
  public double Add(double n1, double n2)
  {
     return n1 + n2;
  }

  [OperationContract]
  public double Subtract(double n1, double n2)
  {
     return n1 - n2;
  }

  [OperationContract]
  public double Multiply(double n1, double n2)
  {
     return n1 * n2;
  }

  [OperationContract]
  public double Divide(double n1, double n2)
  {
     return n1 / n2;
  }
}

<ServiceContract()> _
Public Class CalculatorService
    <OperationContract()> _
    Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double
        Return n1 + n2
    End Function

    <OperationContract()> _
    Public Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double
        Return n1 - n2
    End Function

    <OperationContract()> _
    Public Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double
        Return n1 * n2
    End Function

    <OperationContract()> _
    Public Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double
        Return n1 / n2
    End Function
End Class

The methods that have the OperationContractAttribute class applied use a request-reply message pattern by default. For more information about this message pattern, see How to: Create a Request-Reply Contract. You can also create and use other message patterns by setting properties of the attribute. For more examples, see How to: Create a One-Way Contract and How to: Create a Duplex Contract.

See also