Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where to write the connection string ? in app.config or in web.config?

I am developing MVC application. I have two projects in my application. one is MVC application contains, Controller and Views and the second one is DataLayer project.

I am confused about the where to write the connection string, because while publishing the application it takes the web.config file and I get the data from DataLayer project so should I add connection string in the app.config/Web.config of Data layer project ?

Also, would like to know what is the purpose and difference between app.config and web.config ?

like image 718
bnil Avatar asked Apr 29 '14 11:04

bnil


People also ask

Where do I put connection string?

Connection strings can be stored as key/value pairs in the connectionStrings section of the configuration element of an application configuration file. Child elements include add, clear, and remove.

Where should you store the connection string information?

Connection strings in configuration files are typically stored inside the <connectionStrings> element in the app. config for a Windows application, or the web. config file for an ASP.NET application.

How do you define a connection string in Web config file?

<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System. Data. SqlClient" />


1 Answers

Every project comes with a configuration file when it's created. A general class library has a generic one called app.config. A web project is more specific, so its file is called web.config and comes with web-specific parameters. They both serve the same purpose.

The problem you are facing is that only the executable project's config file (web.config) is deployed by default. You have a few options:

  1. Add your connection string to web.config and pass it to your data layer. This is simple (an most common), but separates the config info from your data layer project.
  2. Have your data layer read web.config using System.Configuration.ConfigurationManager. This alleviates you from passing the data to your data layer, but creates a strong dependency (your data layer will not work without a properly formatted web.config file).
  3. Deploy app.config as XML content and write custom code so that your data layer can read it. This is more work, but it gets your data config out of the web config.
  4. A slight change to #2, you can create a custom config section called "dataLayer" in web.config. This can be read via System.Configuration.ConfigurationManager. I prefer this approach, as it seems like a good balance. You have a custom strongly-typed config section in the "default" config file.

This related question has some good info too.

like image 95
nunzabar Avatar answered Sep 21 '22 21:09

nunzabar