I have the following defined in my “Form1”:
Dim Database As New DatabaseManager
So that I can access all my database functions anywhere in the main form (database connection is initialized via the “private sub new()” function in the DatabaseManager class.
The works fine for all queries done in form1, however I have many other classes I’d like to be able to access the database from.
Does anyone know how to access the initiated class in my example? Since right now it is initiated in the main form, if I try to access any functions inside any other class functions it does nothing (doesn’t error out either).
I’m trying to figoure out how to dim a class one and I can access it from within any class and I can’t figure it out.
Thanks!
One thing you could do is create a factory for the
DatabaseManagerand then just have all your other code call it from that factory. I’m very out of practice with VB syntax, but in C# it might look something like this:VB
The idea then is that anything in your application which needs to use a
DatabaseManagerwould just callDatabaseManagerFactory.Currentto get the one shared instance.Note that in this case
DatabaseManagerisn’t really a singleton, you can still instantiate one elsewhere in the application if you need to for some reason. If it should be an actual singleton then you’d want to make some modifications to theDatabaseManagerclass itself. Maybe give it a private constructor and implement this factory directly on the class? Something like this:VB
(I encourage anybody more familiar with VB syntax to edit this answer accordingly to better address the question.)