0
我想實現一個類,第一次調用時從數據庫中獲取一些數據,隨後對該類的調用將在應用程序的生命週期中返回相同的數據,即使此類的新實例是調用。這可能嗎?Autofac類只實現
這裏是我的示例嘗試,問題是我得到Object not set to an instance of the Object
。
Public Class session
Implements IContainerProviderAccessor
Shared _containerProvider As IContainerProvider
Private _IUserSessionService As IUserSessionService ' interface to stores data
Public Property Usersession As IUserSessionService
Get
Return _IUserSessionService
End Get
Set(value As IUserSessionService)
_IUserSessionService = value
End Set
End Property
Public ReadOnly Property ContainerProvider As IContainerProvider Implements IContainerProviderAccessor.ContainerProvider
Get
Return _containerProvider
End Get
End Property
Public Function GetConnection() As String
Dim UserSessionDetail As New UserSessionDetails
' Do we have a container if not register one
If IsNothing(_containerProvider) Then
RegisterConnection()
Dim UserSessionDetail As New UserSessionDetails
UserSessionDetail.connection_string = GoAndGetOneFromOtherSource
Usersession.AddSession(UserSessionDetail)
Return UserSessionDetail.connection_string
Else
Usersession.GetUserSession()
Return UserSessionDetail.connection_string
End If
End Function
Private Sub RegisterConnection()
Dim builder As ContainerBuilder = New ContainerBuilder()
builder.RegisterType(Of UserSessionService).As(Of IUserSessionService).InstancePerRequest()
'Auto Fac Binding
_containerProvider = New ContainerProvider(builder.Build())
End Sub
End Class
呀,當然這是可能的,定義數據和方法爲靜態,請檢查您是否已經有了數據,如果這樣返回,如果不是,那麼請在取... – Trey
在Autofac而言,這可以通過依賴單身人士對象,或使你的對象成爲單身人士來完成。每當另一個對象聲明對'session'的依賴時,它就會使用同一個對象。說實話,這看起來有點亂。 'IContainerProviderAccessor'應該只用於擴展HttpApplication對象,而不是像這樣。也許回顧[整合文檔](http://autofac.readthedocs.io/en/latest/integration/webforms.html)? –