psobhan
psobhan

Reputation: 645

How to connect to the connection string written in the web.config of the web services

We have a web service project called 'Service' and in the web.config of the 'service' I have set the connection string as follows:

<connectionStrings>
        <add name="ConnectionString" connectionString="Data Source=L308;Initial Catalog=Dashboard;Integrated Security=True"
         providerName="System.Data.SqlClient" />
    </connectionStrings>                                                                 

I am trying to access the connection string from another project 'DBConnector' using the following code but getting null reference exception even though after adding the reference of the 'Service' into 'DBConnector'. using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))

Upvotes: 2

Views: 3198

Answers (4)

Illuminati
Illuminati

Reputation: 4619

'Service' into 'DBConnector'.

Seems to be incorrect thing to do. It should have been other-way around!

Upvotes: 0

Jethro
Jethro

Reputation: 5916

If you need want to make that connection string Global so all you applications and services can use it you will need to put it in the machine.config.

The machine config if found here %WinDir%\Microsoft.NET\Framework\\CONFIG.

Upvotes: 0

Ankur
Ankur

Reputation: 33657

You will need to have the connection string in DBConnector project config file. Adding reference to a project doesn't bring in the config of that project in the main config of the project

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176946

If i got you

You can not do that if you want to use the Connection string of service in you library. You need to expose that as property or method

in you service.cs

public string connectionstring
{
  get
  {
    return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
  }
}

or

DBConnetor added as referance

If the DBconnector has added as referance in the Service layer than you can access it easily by the code you have written

Upvotes: 0

Related Questions