2

我在我的 vb.net 网络应用程序中使用上述库。开发snowmaker的人说你不应该每次想要一个ID时都创建一个新实例,你应该使用一个基本的单例。

我知道单例是什么,但从未使用过它们。我在堆栈溢出时遇到过这个

Public NotInheritable Class MySingleton
    Private Shared ReadOnly _instance As New Lazy(Of MySingleton)(Function() New
        MySingleton(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)

    Private Sub New()
    End Sub

    Public Shared ReadOnly Property Instance() As MySingleton
        Get
            Return _instance.Value
        End Get
    End Property
End Class

这是我用来生成 ID 的代码

Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings("blobStorage").ConnectionString)
Dim ds As New BlobOptimisticDataStore(storageAccount, "container-name")

Dim generator = New UniqueIdGenerator(ds)
Dim ret = generator.NextId(table)

哪个有效,但是我如何将它合并到单例类中,以便我只从我的网络应用程序中调用它一次?

4

1 回答 1

1

单例是一个静态对象,您可以根据需要多次调用它,并确保它一次只运行一个调用。

您不会实例化单例,它就像您只需调用的类级别或全局对象。您尚未包含 UniqueIdGenerator 的代码,但您的代码可能如下所示:

Imports SnowMaker
Imports Microsoft.WindowsAzure.Storage

Module Module1

    Sub Main()
        Dim storageAccount = CloudStorageAccount.Parse("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
        Dim ds As New BlobOptimisticDataStore(storageAccount, "vhds")

        MySingleton.Instance.DataSource = ds
        MySingleton.Instance.Table = "table"
        Dim myid = MySingleton.Instance.NextId
        Dim myid2 = MySingleton.Instance.NextId
        Dim myid3 = MySingleton.Instance.NextId
        Dim myid4 = MySingleton.Instance.NextId

    End Sub

End Module

然后你的单例代码会调用你的生成器

Imports SnowMaker

Public NotInheritable Class MySingleton
    Private Shared ReadOnly _instance = New Lazy(Of MySingleton)(Function() New MySingleton(), System.Threading.LazyThreadSafetyMode.ExecutionAndPublication)
    Private _generator As UniqueIdGenerator

    Private Sub New()
    End Sub

    Public Shared ReadOnly Property Instance() As MySingleton
        Get
            Return _instance.Value
        End Get
    End Property

    Private _ds As BlobOptimisticDataStore
    Public Property DataSource() As BlobOptimisticDataStore
        Get
            Return _ds
        End Get
        Set(ByVal value As BlobOptimisticDataStore)
            _ds = value
        End Set
    End Property

    Private _tableName As String
    Public Property Table() As String
        Get
            Return _tableName
        End Get
        Set(ByVal value As String)
            _tableName = value
        End Set
    End Property

    Private _Id As Integer
    Public ReadOnly Property NextId() As Integer
        Get
            If _generator Is Nothing Then
                _generator = New UniqueIdGenerator(_ds)
            End If
            Return _generator.NextId(_tableName)
        End Get
    End Property

End Class
于 2013-08-14T15:17:03.157 回答