Named Database Instance

Topics: Data Access Application Block
Jul 6, 2010 at 10:47 PM
I would like to loop thru the connection strings in the app.config file and for each one create a Named Database Instance. How do I construct the class in C#, it will not let me use a string variable in the constructor for the Database Name i.e. "Sales". I am new to dependency attributes and do not know how to do this. Thanks, nplumb public class ExampleScenario { private Database db; public ExampleScenario([Dependency("Sales")] Database theDatabase) { db = theDatabase; } ... }
Jul 7, 2010 at 2:59 AM

Here's a sample code to loop each connection string in the configuration file:

for (int ctr = 0; ctr < ConfigurationManager.ConnectionStrings.Count; ctr++ )
        //use ConfigurationManager.ConnectionStrings[ctr].Name to access each connection string name

However, if you're using the Dependency attribute specifying the name of the connection string, if you resolve for an instance of that class, for example in your code snippet above, you're actually saying that for every call to resolve for an ExampleScenario class, inject a Database instance using the connection string named "Sales".   To obtain an instance of ExampleScenario for each connection string in the app.config, you can use this code if you're using Enterprise Library 5.0

for (int ctr = 0; ctr < ConfigurationManager.ConnectionStrings.Count; ctr++ )
                ExampleScenario example = container.Resolve<ExampleScenario>(
                    new ParameterOverride("theDatabase", 

However, if you're using version 4.x, passing ResolverOverrides(in this case, the ParameterOverride) in the Resolve method isn't supported so you would need to create registrations for the ExampleScenario class for each connection string.

Did I answer your question or this isn't exactly what you want?


Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.