Get connection string in class library project in a solution

孤者浪人 提交于 2019-11-30 14:37:24

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!