views:

64

answers:

2

hi, I am developing a class library (C#) that i will use it for my different projects (later). My class library dll will use the connection string /data context of the project which will reference my new dll. How can i do it?
Lets say i have a class Library Project named "CLP", and a website project "WP". I can add reference to CLP.dll file but how i will pass a connection string/data context object to that dll? as CLP.dll will access db based on the connection string of the "WP".

Not sure my problem is clear or not!

+1  A: 

If you develop your class library and it requires a connection string called "ConnectionString" as long as the project you call it from has a connection string in its web/app config file of "ConnectionString" then it should be fine.

So using your project names. Your "CLP" class project with your data access code in will setup a connection using the string "ConnectionString":

_serverConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

and then you code against that connection.

In the web.config file in your web project ("WP") you add the following:

  <connectionStrings><add name="ConnectionString" connectionString="Data Source=.\SQL2008;Integrated Security=True" providerName="System.Data.SqlClient" /></connectionStrings>

Obviously pointing to the data source etc you are using for the "WP" project.

Hope this helps.

WestDiscGolf
This way i will bound to use the same connection string name on all my other project which will add reference to "CPL". Not any generic way that i can easily pass the connection string name to "CPL" dll?
coure06
In a word yes, see @SlackerCoder's response. The parameter would be the connection strings configuration setting key which you want to look up from the config section :-)
WestDiscGolf
Thinking about it; you could build on the way @SlackerCoder suggested, by also writing the data access dll in a factory pattern. If you wanted to get really carried away, you could make it have a fluid interface and have dependancy injection points to aid in unit testing. Just throwing some ideas out there.
WestDiscGolf
A: 

Just to add on @WestDiscGolf's answer:

You can also use a parameter to pass in the name of the connectionstring from the config file (so you dont always have to use "ConnectionString").

For example: In your DLL class you can have:

public void buildConnection(string sConnectionString){
   //Some code, variables, etc

   _serverConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[sConnectionString]);

   //Some more code, etc etc

}

and calling it:

buildConnection("MyConnectionStringNameInTheConfigFile");

**Note: I use void for the return type as a sample, if you have a return, just replace it. I dont know your project, so I dont want to make assumptions how you are going to use the connection!!

SlackerCoder