如何:控制服务实例化

通过设置服务的实例模式,可以指定创建 System.ServiceModel.InstanceContext(及其关联的用户定义服务对象)的时间。有关可能的模式,请参见 InstanceContextMode 枚举。有关行为的更多信息,请参见使用行为配置和扩展运行时。有关工作示例,请参见Service: Behaviors Samples

使用代码控制服务实例生存期

  1. ServiceBehaviorAttribute 应用于服务类。

  2. InstanceContextMode 属性设置为下列值之一:PerCallPerSessionSingle

    <ServiceBehaviorAttribute(InstanceContextMode:=InstanceContextMode.PerCall)> _
    Public Class CalculatorService
    
    [ServiceBehaviorAttribute(InstanceContextMode = InstanceContextMode.PerCall)]
    

示例

下面的代码示例将 ServiceBehaviorAttribute 属性(attribute)的 InstanceContextMode 属性(property)设置为 PerCall

' 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
// 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;
    }
}

另请参见

参考

ServiceBehaviorAttribute
InstanceContextMode
InstanceContextMode

其他资源

Service: Behaviors Samples