0

I am strugling to get the proper/best way to handle a connection string in an other project:

I have two projects in a VS solution:

  1. Project 1: website (asp.net)

    • with web.config has a db connection string
  2. Project 2: with some classes

    • with data layer (to be accessed in project 1 or project x)

What is the proper way to set the connection string in project 2?

Project 2 has a static class with function like:

public static List<T> GetData();

Should I always pass the connection string as an variable like:

public static List<T> GetData(string connectionString);

So syntax like i.e.:

var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connectionStringName"];
var list = ClassX.GetData(connectionString);

Or is it possible to set in general somewhere in an other way?

Or is my complete setup wrong? :)

M.P.
  • 262
  • 1
  • 11

4 Answers4

2

We usually put the connection string in the website (Main Entry Point), and we can read it from the class library (Project 2).

Just add a reference for System.Configuration in your class library and you're good to go and read the config from project 1 as if you're executing the code in project 1 directly.

Zein Makki
  • 29,485
  • 6
  • 52
  • 63
2

class libraries do not have their own configuration. They use the configuration of which ever executable they are being used in.

This means that for you you should be able to use the same code, and it will read the setting from the config (assuming that it is there).

krish
  • 881
  • 7
  • 11
1

Some good ways described are as:

Put common configuration settings in machine.config as shown here

Also look at this which shows how to share same app.config file (assume you can place connection string in this) between multiple project in the same solution.

Sharing App.config between projects

Community
  • 1
  • 1
Sami
  • 3,686
  • 4
  • 17
  • 28
0

It's not important to define a connection string in both projects, just add in on your config file of Project 1: website (asp.net) that is your default project.

<connectionStrings>
    <add name="Context" connectionString="Server=ServerName; User ID=sa; Password=123; Database = DBName;"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

more information on : http://www.connectionstrings.com/

Saeid Mirzaei
  • 950
  • 2
  • 18
  • 48