Master Me Now
Master Me Now

Reputation: 83

How to use only one connection string accross one solution?

I have a solution where I have more than 10 projects and in each project I need to connect to database. Is there anyway to centralize and get connection string only from one web.config file?

Upvotes: 1

Views: 711

Answers (3)

Steve Wellens
Steve Wellens

Reputation: 20620

If you really have a Data Layer as you've indicated, it should be the only module/project that needs a connection string.

Upvotes: 1

SLaks
SLaks

Reputation: 887433

Just put the connection strings inside the Web.config.

Library projects don't have their own config files; instead, they use the AppDomain's configuration file, which in your case would be the Web.config.

Upvotes: 1

Christian
Christian

Reputation: 3972

inside your web.config put

<configuration>
    <connectionStrings configSource="connstrings.config"/>
</configuration>

create a file in the root directory of your website called connstring.config and put the following inside it

<?xml version="1.0"?>
<connectionStrings>
    <add name="local"
         connectionString="Data Source=dbserver;Initial Catalog=databasename;Integrated Security=True;Pooling=false;Connect Timeout=5;"
         providerName="System.Data.SqlClient" />
</connectionStrings>

create class in your project called Database.cs and put the following in it

using System.Configuration;
public class Database
{
    public class ConnStrings
    {
        public static string local = ConfigurationManager.ConnectionStrings["local"].ConnectionString;
    }
}

now whenever you need the conn string, you can use Database.ConnStrings.local

Upvotes: 0

Related Questions