Marco
Marco

Reputation: 1

can I create singletons with in class?

I want to generate a set of classes/singeltons to access a sqlserver database. I'm aware things like entity-framework exist but I want my own sollution. Observe the pseudo-code below

Class Database
    Dim ConnectionX As SqlClient.SqlConnection
    
    Function getDataTable(Query As String) As DataTable
        Uses ConnectionX
    End Function
    
    ?:Schema1
        Structure Table1
            Dim Field1
            Dim Field2
        End Structure
        
        Function Insert_Table1(Field1, Field2) As Table1
            Uses ConnectionX
        End Function
        
        Function Update_Table1(Field1, Field2) As Table1
            Uses ConnectionX
        End Function        
        
        Sub Delete_Table1(Field1) 
            Uses ConnectionX
        End Sub     
    
    

I want multiple instances of the class "Database" so that I can vary the connection-string to access D, T, A of P The classes/singletons/structures "Schema" represents the schema's in the database (the '?' above). I do NOT want multiple instances of a Schema. Within the Schema there are structures that represent tables, views and table-valued-functions in the schema Under schema I need functions to insert, update and delete into/from a table using the connection from the database.

Can this be done in VB?

Upvotes: 0

Views: 44

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

If I'm understanding you correctly, an option would be to make the constructor for the class Private and use a Shared method to get an instance based on connection string. If an instance already exists for the connection string provided then return that, otherwise create a new instance.

Public Class Database

    Private Shared ReadOnly instances As New List(Of Database)

    Public Shared Function GetInstance(connectionString As String) As Database
        Dim instance = instances.SingleOrDefault(Function(db) db.ConnectionString)

        If instance Is Nothing Then
            instance = New Database(connectionString)
            instances.Add(instance)
        End If

        Return instance
    End Function

    Public ReadOnly Property ConnectionString As String

    Private Sub New(connectionString As String)
        Me.ConnectionString = connectionString
    End Sub

    '...

End Class

You would then do something like this in code whenever you needed an instance:

Dim db = Database.GetInstance("Data Source=MyServer;Initial Catalog=MyDatabase;Integrated Security=SSPI;")

One thing to keep in mind is that you can actually have effectively equal connection strings that are NOT equal as String objects so you might want to use slightly more rigorous comparisons inside your class. I'll leave that decision and implementation up to you though.

Upvotes: 2

Related Questions