简体   繁体   中英

Get connection string in class library project in a solution

In my .net 4 solution, i have two different projects- an web application project and a class library project.

In web application project, database connection string is in web.config file. I would like to access that connection string from class library project. Is it possible? if yes, how?

If there is any better approach to get connection string, please let me know.

To access it from your class library add a reference to System.Configuration then use System.Confinguration.ConfigurationManager.ConnectionStrings .

It's not ideal to read this from a class library. After all, can you say that your class library will always be consumed by something with a configuration file? Certainly not if you share it with other developers, especially of different platforms.

Consider:

  1. IoC - use dependency injection to provide a dependency that contains configuration settings. These would be populated by the consuming library (web app).
  2. Pass the settings to the class library when consuming elements that depend on them.

eg:

public class MyLibraryContainer
{
    private string _connectionString;

    public MyLibraryContainer(string connectionString)
    {
        _connectionString = connectionString;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM