Web服务作为单例是否会导致不同用户的问题?

时间:2010-06-23 12:03:34

标签: asp.net vb.net web-services

我正在开发一个使用UPS运送网络服务的电子商务应用。我已经读过创建一个单例是好的,所以任何时候都只有一个webservice实例。我的代码如下。

Public Class Ship
    Private Shared sync As New Object()
    Private Shared _Service As New ShipService

    Public Shared ReadOnly Property Service As ShipService
        Get
            If _Service Is Nothing Then
                SyncLock sync
                    If _Service Is Nothing Then
                        _Service = New ShipService
                    End If
                End SyncLock
            End If
            Return _Service
        End Get
    End Property

    Public Shared Function GetInstance() As ShipService
        Return Service()
    End Function
End Class

以下是将使用它的片段。

Public Sub New(ByVal ToAddress As Address, ByVal WeightInLbs As String)
    //Not relevant code
    Ship.Service.UPSSecurityValue = Security
    //More not relevant code 
End Sub

Public Function ProcessShipment() As ShipmentResponse
    Return Ship.Service.ProcessShipment(ShipmentRequest)
End Function

在构造函数的上面一行中,我必须设置服务的UPSSecurityValue。然后我将调用ProcessShipment函数。我的问题是;由于web服务被作为单身人士进行交易,因此应用程序的不同实例可以共享相同的UPSSecurityValue,并且可以在我设置它和调用ProcessShipment之间进行更改吗?

1 个答案:

答案 0 :(得分:1)

如果您正在做什么,它可以在您调用New并设置Security值和实际处理货件时明确更改。单例在应用程序的所有用户之间共享(在同一个Web应用程序中,即 - 如果您在服务器上有此应用程序的多个副本,他们每个人都使用自己的单例),因此所有用户将共享相同的数据

如果多个用户同时运行该应用程序(或User2仅落后1ms):

User1                           User2
New (sets security code)
                                New (sets security code)
ProcessShipment
                                ProcessShipment 

两个货件都将使用User2的安全代码进行处理,这不是您想要的。安全地执行此操作的方法可能是在您发送包时将安全性传递给函数,然后立即使用它 - 如果您将其存储以供以后使用,即使是稍后的单个指令,您也可以为自己做好准备用户阅读彼此数据的条件。