Get connection string in class library project in a solution

后端 未结 1 1152
别那么骄傲
别那么骄傲 2021-01-02 19:52

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

1条回答
  •  孤街浪徒
    2021-01-02 20:26

    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.

    e.g.:

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

    0 讨论(0)
提交回复
热议问题