5

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>

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.