AlexGH AlexGH - 9 months ago 110
C# Question

read connectionstring from WebConfig file in dll

I have a

class library project(dll)
and an
project(I'm using Core
framework). How can I read the
that is inside the
file of my MVC project in the
? I'm inside the
and I need to read it, I don't want to put the
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 Source

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;
   //connection string not found
//instantiating class from the class library
var myFoo = new Foo(conStr);