Question

I have created a class library in VB .NET. Some code in the library connects to the database. I want to create a config file that would hold the connection string.

I have created a "Settings.settings" file and stored the connection string in there.

When a class library having a settings file is built, it generates a ".dll.config" file which has the key value pairs defined in the settings file.

Problem with this is when i change the connection string in the ".dll.config" file, the library does not references these changes. I would still need to recompile the class library which would then overwrite my changes in the .dll.config file.

I need to be able to change the connection strings on the fly without having to recompile the library.

Is there a mechanism in VB.NET class library (.NET 2.0) that would let me do this?

Passing the connection string to the class library from the web page that uses its method is not a option.

I have listed a sample below, this is how i would access the string.

    Public Function getsettings(ByVal Setting As String) As String
        If Setting = "Demo" Then
            Return My.Settings.Demo
        Else
            Return My.Settings.Live
        End If
    End Function
Was it helpful?

Solution

If you have an application which uses your library called MyApp, then the connection string defined in MyApp.exe.config will be available to your library. Generally speaking the client program should set the configuration environment, not the library.

If GetApplicationSetting("connectionString") Is Nothing Then
    Throw New Exception("Could not retrieve connection string from .config file")
Else
    Return ConfigurationManager.AppSettings.Item("connectionString")
End If

Make sure you have the System.Configuration framework loaded to access the ConfigurationManager.

EDIT 1: If you are using it in a web-application, then set the connection string in web.config.

EDIT 2: If you set the connection string in the ConnectionStrings section of the .exe.config or web.config you can access it using :

ConfigurationManager.ConnectionStrings("MyConnectionString")

OTHER TIPS

Config files are specific to the application. So if your DLL is used by an application, the app.config or web.config needs to have the entries you are trying to use in the DLL config.

Unfortunately the "Not an option" is probably the correct option.

We have multiple libraries that have the same requirement. We set it up so that our class library directly retrieves the connection string from the web.config file of the application that is using it. When you say:

Passing the connection string to the class library from the web page that uses its method is not a option.

In theory, the web page is not passing the con str as a parameter, but the class library is just directly taking it from the web.config file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top