AlexGH AlexGH - 11 days ago 6
C# Question

read connectionstring from WebConfig file in dll

I have a

class library project(dll)
and an
MVC
project(I'm using
ASP.net Core
with
.net
framework). How can I read the
connectionstring
that is inside the
WebConfig
file of my MVC project in the
dll
? I'm inside the
dll
and I need to read it, I don't want to put the
connectionstring
hardcoded in there too if I have it already inside the WebConfig of the MVC project, how could I do that?
I'm using in my dll this code but it's not working:

var connectionString = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;

Answer

Pass the connection string in as an argument when you use / instantiate your class from the class library rather than attempting to access web.config directly from the class library. This is a fairly common practice and will be more recognizable to other people who may need to maintain your code.

//in the MVC code somewhere
string conStr = null;
if(ConfigurationManager.ConnectionStrings["MyConnectionStringName"] != null)
   conStr = ConfigurationManager.ConnectionStrings["MyConnectionStringName"].ConnectionString;
else
{
   //connection string not found
}
//instantiating class from the class library
var myFoo = new Foo(conStr);