'Copyright (c) Telerik.  All rights reserved.
'
' usage example:
'
' ' Get ObjectScope from Helper
' Dim scope As IObjectScope = ObjectScopeProvider1.ObjectScope
' ' start transaction
' scope.Transaction.Begin()
' ' create new persistent object person and add to scope
' Dim p As New Person
' scope.Add(p)
' ' commit transction
' scope.Transaction.Commit()
'
Imports Telerik.OpenAccess
Imports Telerik.OpenAccess.Util

Public Class ServiceScopeProvider
    Implements IObjectScopeProvider
    Private _myDatabase As Database
    Private _myScope As IObjectScope

    Private Shared theObjectScopeProvider1 As ServiceScopeProvider

    Public Sub New()
    End Sub

    ' Allows a dynamically loaded assembly to open the database.
    ' Must be called before the ObjectScope is aquired.
    Public Shared Sub AdjustForDynamicLoad()
        If theObjectScopeProvider1 Is Nothing Then
            theObjectScopeProvider1 = New ServiceScopeProvider()
        End If

        If theObjectScopeProvider1._myDatabase Is Nothing Then
            Dim assumedInitialConfiguration As String
            assumedInitialConfiguration = "<openaccess>" _
                           & "<references>" _
                           & "<reference assemblyname='PLACEHOLDER' configrequired='True'/>" _
                           & "</references>" _
                           & "</openaccess>"
            Dim repl As String = "PLACEHOLDER"
            Dim dll As System.Reflection.Assembly = theObjectScopeProvider1.GetType().Assembly
            assumedInitialConfiguration = assumedInitialConfiguration.Replace(repl, dll.GetName().Name)
            Dim xmlDoc As New System.Xml.XmlDocument
            xmlDoc.LoadXml(assumedInitialConfiguration)
            Dim allDlls As System.Reflection.Assembly() = New System.Reflection.Assembly() {dll}

            theObjectScopeProvider1._myDatabase = Telerik.OpenAccess.Database.Get("MyDatabaseConnetion", _
           xmlDoc.DocumentElement, allDlls)
        End If
    End Sub

    Public Shared Function Database() As Database
        If theObjectScopeProvider1 Is Nothing Then
            theObjectScopeProvider1 = New ServiceScopeProvider()
        End If

        If theObjectScopeProvider1._myDatabase Is Nothing Then
            theObjectScopeProvider1._myDatabase = Telerik.OpenAccess.Database.Get("MyDatabaseConnetion")
        End If

        Return theObjectScopeProvider1._myDatabase
    End Function

    Public Shared Function ObjectScope() As IObjectScope
        Database()

        If theObjectScopeProvider1._myScope Is Nothing Then
            theObjectScopeProvider1._myScope = GetNewObjectScope()
        End If

        Return theObjectScopeProvider1._myScope
    End Function

    Public Shared Function GetNewObjectScope() As IObjectScope
        Dim db As Database = Database()

        Dim newScope As IObjectScope = db.GetObjectScope()
        Return newScope
    End Function
End Class
