How to access a connection string from within a library

五迷三道 提交于 2019-12-06 02:38:20

问题


I have a web project (mvc) and data access layer in a separated class library project. I need to access to a connection string in app.config which sits in that library project.

ConfigurationManager.ConnectionStrings[0].ConnectionString pulls something strange. I don't have this kind of settings neither in the library's config nor in the web project's config files.

the App.config looks like that:

<?xml version="1.0" encoding="utf-8" ?>
 <configuration>
  <connectionStrings>
   <add name="DALConnectionString" connectionString="User ID=sa;Password=pass;Initial     Catalog=db;Data Source=srv\SQL2005;" />
 </connectionStrings>
</configuration>

回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/5222262/how-to-access-a-connection-string-from-within-a-library

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