views:

143

answers:

2

We have a website that we would like to extrapolate user controls from and put them into an assembly of their own. This is so we can more easily reuse these controls in other similar projects. I think we can do this fairly easily by creating a new class library project, moving the .ascx and .ascx.cs files over to this project, adding the appropriate .net assembly references, and modifying our project's references to these user controls to pull them from the library.

The problem I'm foreseeing at this point is that these controls are heavily dependent on a certain database schema. Historically, we have always kept our connection strings in the web.config, and have been using LINQ to SQL for our database management, so I am having trouble conjuring up a "best-practices" way to share database connection information in the web.config with the assembly. The only way I could think of doing it is to add a ConnectionString property to each of my user controls, and on Page_Load, set the ConnectionString property (which will in turn create an instance of the data context using that connection string). However, I was hoping to instead accomplish one of the following:

  • Somehow have the assembly pull the connection string directly from the web.config. Since the assembly is not a web application, I obviously can't just call ConfigurationManager.ConnectionStrings["connection"]. Is this possible?
  • Less likely, but figure out a way to set the connection string once on application start and have each instance of my user controls somehow reuse this. I would think there would be a way to cache this value for reuse by the assembly, but I can't think of a way to do it.

Any suggestions are greatly appreciated.

+1  A: 

The controls will use whatever connection strings are included in the config of the calling application. There is no need for a seperate config.

I obviously can't just call ConfigurationManager.ConnectionStrings["connection"]. Is this possible??

Yes!

grenade
To clarify, the question is HOW can I pull the connection string information from the web site's web.config from within the assembly.
Keith
The string is pulled in at runtime, when the assembly is being called by an app/website that has a config. It doesn't need one of its own.
grenade
Awesome, guess I should try it out.
Keith
Worked like a charm - if I would have just tried it for myself, I would have answered my own question...
Keith
indeed, but now you know...
grenade
A: 

Calls to System.Configuration.ConfigurationManager.ConnectionStrings will return results from the application's web.config even if the calling code is placed in it's own assembly. Remember: it's not assembly.config, it's web.config.

If your user controls are expecting a connection string named "MyDatabase" then every web application that they're used in will need a MyDatabase connection string defined in its web.config.

Ken Browning