How to access a connection string from within a library
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="Us开发者_如何学Goer ID=sa;Password=pass;Initial Catalog=db;Data Source=srv\SQL2005;" />
</connectionStrings>
</configuration>
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.
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.
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.
精彩评论