作法:控制服務執行個體
設定服務的執行個體模式,可讓您指定 System.ServiceModel.InstanceContext (及其相關之使用者定義的服務物件) 建立的時機。 如需可能的模式,請參閱 InstanceContextMode 列舉。 如需行為的詳細資訊,請參閱使用行為設定和擴充執行時間。 如需工作範例,請參閱行為。
使用程式碼控制服務執行個體存留期
將 ServiceBehaviorAttribute 套用至服務類別。
將 InstanceContextMode 屬性設定為下列其中一值:PerCall、PerSession 或 Single。
[ServiceBehaviorAttribute(InstanceContextMode = InstanceContextMode.PerCall)]
<ServiceBehaviorAttribute(InstanceContextMode:=InstanceContextMode.PerCall)> _ Public Class CalculatorService
範例
下列程式碼範例會將 InstanceContextMode 屬性 (Attribute) 的 ServiceBehaviorAttribute 屬性 (Property) 設定為 PerCall。
// Define a service contract.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
// Service class which implements the service contract.
[ServiceBehaviorAttribute(InstanceContextMode = InstanceContextMode.PerCall)]
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
return n1 + n2;
}
public double Subtract(double n1, double n2)
{
return n1 - n2;
}
public double Multiply(double n1, double n2)
{
return n1 * n2;
}
public double Divide(double n1, double n2)
{
return n1 / n2;
}
}
' Define a service contract.
<ServiceContract([Namespace]:="http://Microsoft.ServiceModel.Samples")> _
Public Interface ICalculator
<OperationContract()> _
Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double
<OperationContract()> _
Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double
<OperationContract()> _
Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double
<OperationContract()> _
Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double
End Interface
' Service class which implements the service contract.
<ServiceBehaviorAttribute(InstanceContextMode:=InstanceContextMode.PerCall)> _
Public Class CalculatorService
Implements ICalculator
Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double _
Implements ICalculator.Add
Return n1 + n2
End Function
Public Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double _
Implements ICalculator.Subtract
Return n1 - n2
End Function
Public Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double _
Implements ICalculator.Multiply
Return n1 * n2
End Function
Public Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double _
Implements ICalculator.Divide
Return n1 / n2
End Function
End Class