Sharing a connection string
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开发者_Go百科 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!
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.
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!!
精彩评论