作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在我的 vb.net Web 应用程序中使用上述库。开发造雪机的人说,你不应该每次需要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)
这可行,但是如何将其合并到单例类中,以便我只从我的网络应用程序中调用它一次?
最佳答案
单例是一种静态对象,您可以根据需要多次调用它,并且确保它一次只会运行一个调用。
您不实例化单例,它就像您只是调用的类级别或全局对象。您尚未包含 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
关于vb.net - 适用于 Azure 的 SnowMaker .Net 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18231172/
我在我的 vb.net Web 应用程序中使用上述库。开发造雪机的人说,你不应该每次需要ID时都创建一个新实例,你应该使用基本的单例。 我知道什么是单例,但从未使用过它们。我在堆栈溢出时遇到过这个 P
我在我的 vb.net Web 应用程序中使用上述库。开发造雪机的人说,你不应该每次需要ID时都创建一个新实例,你应该使用基本的单例。 我知道什么是单例,但从未使用过它们。我在堆栈溢出时遇到过这个 P
我是一名优秀的程序员,十分优秀!