服務是一種類別,可公開用戶端在一或多個端點上可用的功能。 若要建立服務,請撰寫實作 Windows Communication Foundation (WCF) 合約的類別。 您可以使用下列兩種方式之一來執行此動作。 您可以將合約個別定義為介面,然後建立實作該介面的類別。 或者,您可以將 ServiceContractAttribute 屬性直接放在類別本身上,並將 OperationContractAttribute 屬性放在服務用戶端可用的方法上,以直接建立類別和合約。
建立服務類別
以下是一個實作出已經被單獨定義的合約的IMath
服務範例。
// Define the IMath contract.
[ServiceContract]
public interface IMath
{
[OperationContract]
double Add(double A, double B);
[OperationContract]
double Multiply (double A, double B);
}
// Implement the IMath contract in the MathService class.
public class MathService : IMath
{
public double Add (double A, double B) { return A + B; }
public double Multiply (double A, double B) { return A * B; }
}
或者,服務可以直接公開合約。 以下是定義和實作MathService
合約的服務類別範例。
// Define the MathService contract directly on the service class.
[ServiceContract]
class MathService
{
[OperationContract]
public double Add(double A, double B) { return A + B; }
[OperationContract]
private double Multiply (double A, double B) { return A * B; }
}
請注意,上述服務會公開不同的合約,因為合約名稱不同。 在第一個案例中,公開的合約會命名為 “IMath
”,而在第二個案例中,合約會命名為 “MathService
”。
您可以在服務和操作實作層級設定一些選項,例如平行處理和實例。 如需詳細資訊,請參閱 設計和實作服務。
實作服務合約之後,您必須為服務建立一或多個端點。 如需詳細資訊,請參閱 端點建立概觀。 如需如何執行服務的詳細資訊,請參閱 裝載服務。