0

Right now I'm able to establish a connection within my class by calling it in each method by doing the following.

    Dim sConnectionString As String = ConfigurationManager.AppSettings("Blah")
    'Establish connection with db
    Dim cnSqlConnection1 As New SqlConnection(sConnectionString)

Only problem is that I have to call it in each method. I was told that it was better to create a constructor for the class nad have the connection string it uses passed into the constructor.

Here's my attempt but can't seem to figure out since I'm still unable to reach it in the method.

Public Sub New(ByVal sConnectionString As String)
    sConnectionString = ConfigurationManager.AppSettings("Blah")
End Sub

What is the best way to do it? Thanks in advance.

2 Answers 2

1

You should store the passed connectionstring in a global variable available in all of your class methods

Public Clas MyClass

    Private String gs_conString

    Public Sub New(ByVal sConnectionString As String)
       gs_conString = sConnectionString
    End Sub

    Public Sub AMethod()
        'Establish connection with db
        Dim cnSqlConnection1 As New SqlConnection(gs_conString)
        .....
    End Sub 
    .....

End Class

Of course this means that every time you create an instance of this class you need to pass the connection string to your constructor

Dim cl As MyClass = new MyClass(ConfigurationManager.AppSettings("Blah"))

So it is probably better to use the constructor to extract the connection string automatically everytime you create an instance

Private String gs_conString

Public Sub New()
   gs_conString = ConfigurationManager.AppSettings("Blah")
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for
1

Go with the first option, putting the connection string in the constructor. You don't want your class to depend directly on <appSettings>.

Your class's interface should indicate what dependencies it has. When you put the connection string in the constructor, the class says, "Hey, I need a connection string!"

If the class calls <appSettings> then a user of the class has no way of knowing that the class expects to find a connection string there unless they open your code and read it. If they don't know that the connection string belongs there then they'll get a null reference exception with no explanation.

That raises the question - whatever class creates your class, where does it get the connection string so it can pass it to the constructor? Dependency injection is the answer. It enables you to write classes that way then "wire it up" so that the correct arguments get passed to your constructors.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.