I am trying to build a Data Access Layer for a SQL Server back end.
My class has a number of methods in it.
The constructor takes a connection string.
I currently have to instantiate an object in order to use one of my methods.
So I end up doing this quite a lot in my app.
If I change all of the methods to be Shared does that mean I can just use
them without instantiaing an instance of my DAL class?
Yes.
If so, does that mean the constructor does not run?
Yes - but you can force code to run before any method is called (if
that's the behaviour you're after).
If so, how will my class methods know the ConnectionString value???
Is there a default connection string? If so, put it in a shared
property of your class and use the property everywhere else. If there
is no default connection string, you can work along another model:
1) Force the developer to instantiate a singleton (which accepts the
connection string as a parameter).
2) The singleton stores its instance (Me) in a shared property.
3) DAL makes use of the shared property.
i.e.
Public Class MyDatabase
Private Shared mInstance As MyDatabase = Nothing
Private mConnectionString As String
Private Sub New(oConnectionString As String)
mConnectionString = oConnectionString
End Sub
' This method is used by the BLL
Public Shared Function GetInstance(oConnectionString As String) _
As MyDatabase
If mInstance Is Nothing Then
mInstance = New MyDatabase( oConnectionString )
End Function
Return mInstance
End Function
' This method is used by the DAL
Friend Shared Function GetCurrentInstance() As MyDatabase
Return mInstance
End Function
End Class
The BLL developer would then have a single global, something like:
Public gDatabase As MyDatabase = MyDatabase.GetInstance(
Config.ConnectionString )
Can someone please outline the best way to resolve this?
Thanks!
There are many ways to implement a DAL. I guess you're trying to do
the right thing in that you are trying to make the interface as simple
as possible, right?
The way I prefer is to have an object to represent a Schema. The
Schema object knows how to communicate with Factory objects. Factory
objects know how to create (execute SQL), update, delete & find
DatabaseObject objects. And a DatabaseObject has a private member
indicating the schema it is associated with (so it can provide default
Save() and Delete() methods, and communicate with other factories).
From this model, you can tell that the only driver-dependent parts are
in the Factory objects (SQL Server, Oracle, Access...). Implementing
IDatabaseObject, IFactory and ISchema interfaces allows you to swap
database type. You might also want to spend five minutes specialising
a DataView (which implements the associated IObjectCollection) to wrap
your DatabaseObject.
Rgds,