2

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
4

3 回答 3

3

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")
于 2008-12-10T15:57:33.327 回答
1

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.

于 2008-12-10T15:58:15.370 回答
1

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.

于 2008-12-10T16:03:16.983 回答