Where should I put my connection strings in my class library and how do I access them?

I have a solution with 4/5 projects.

Currently, I have a connection string for my domain project, hardcoded in a C # file.

I would like to put this in a web.config file or something like that. From what I read here and elsewhere, should I store these connection strings in the web configuration of the calling application?

If so, how do I access it?

When I do something like this in my class library:

ConnectionStringSettingsCollection connectionStrings = connectionStringsSection.ConnectionStrings; 

Could not find type or namespace, is there a link or something else missing?

+6
source share
4 answers

An existing schema exists for the connection strings in the config schema.

This applies to the <configuration> element:

 <connectionStrings> <add name="example" connectionString="..."/> </connectionStrings> 

In your code, you must use the ConfigurationManager to access them. To have a link to it, you need to add a namespace using System.Configuration; into your file and a link to System.Configuration.dll for assembly into your project (if it does not already exist).

 string conn = ConfigurationManager.ConnectionStrings["example"]; 
+4
source

You need to add a link to System.Configuration in your main project.

then you can access a connection string like this ...

 System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;//<- last bit for a string version of the full connection string 

ConfigurationManager will also allow you to access a number of other useful properties from your web.config file (this will also work for the application. Configuration files)

+5
source

Define your main application and access the lib class

ConnectionStrings: add using System.Configuration; add ref: System.Configuration;

 ConfigurationManager.ConnectionStrings["key"] 

alternetive

 System.Configuration.ConfigurationSettings.AppSettings["key"]) 
+3
source

use this inside your code.

 String sqlDbConn = ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString(); 

the name must also be specified in your web configuration;

 <connectionStrings> <add name="ApplicationServices" connectionString="You database information" /> </connectionStrings> 

as well as add using System.Configuration; Namespace

0
source

Source: https://habr.com/ru/post/909076/


All Articles