Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access web.config from separate Class Library?

I'm looking for a good way to achieve the following:

I have a web application (MVC 3), with a separate Class Library that contains the back-end logic of a CMS that I'm making. This CMS uses NHibernate to connect to a database. I want the user to be able to configure the connectionstring (and eventually even the flavour of the database) in their web.config file.

What I'm looking for is a good way to get the connection string from the web.config file, even though the DLL is completely separate. Is this possible? Will I have to pass my connection string to my class library somehow? Or will I be able to access it when the application runs?

If I have to create some code in my web application to pass the connection string to my Class Library, how can I make this code as portable as possible, so I won't have to write it again for my next webapp?

Thanks a lot for any ideas you have.

like image 579
Steven Lemmens Avatar asked Oct 04 '11 18:10

Steven Lemmens


1 Answers

You can pass in the connection string to the classes in the class library from the web site.

This is a better choice than trying to get the information directly from the configuration file, as otherwise you will have a dependency on the configuration file existing with the exact right key (making testing the class somewhat harder).

See this blog post for arguments against accessing configuration directly (which is very commonly done, but is not best practice).

like image 56
Oded Avatar answered Oct 14 '22 14:10

Oded