How to access a connection string from within a library

心已入冬 提交于 2019-12-04 06:58:09

By default, a class library can't access a config file.

The client of the class library, in this case your web project, can provide config settings.

Therefore, put all the relevant settings, the connection strings, in the web's config file. The ConfigurationManager code in the class library will use the web projects config settings.

Your library should use dependency injection in this case for inversion of control.

Your class in the data access layer (DAL) library should take the connection string as a constructor argument or a property value.

This will make sure that your DAL can be used in other projects also and is not tied to your your mvc web application.

Let the code which will consume the DAL read the connection string from the config file and inject it into your class's constructor.

you should add the fragment shown above in the web.config then at runtime the configuration manager will use it even if running inside your class library.

You cannot access a app.config for a DLL.

app.config only works for the entry point assembly or web.config for a web project.

Try copying the connection to the entry point config or load the config by parsing the configuration XML - not recommended.

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