Say I have an application with the following structure.
// ASP.NET MVC (Web Project)
// Service/Business Layer (Class Library)
// DAL (Class Library)
Initially I wanted to use an App.config file in the DAL class library which would hold app settings like this:
<appSettings>
<add key="DAL-Assembly" value="DAL.LinqToSql.DataContexts"/>
<add key="DAL-Type" value="DAL.LinqToSql.DataContexts.MyDataContext" />
</appSettings>
And then I would use a factory to create the data context using reflection
public static DataContext GetContext()
{
string assembly = ConfigurationManager.AppSettings("DAL-Assembly");
string type = ConfigurationManager.AppSettings("DAL-Type");
Assembly a = Assembly.Load(assembly);
return (DataContext)a.CreateInstance(type);
}
The problem is that now I understand that a Class Library has to use the configuration file of the calling application. Which means that it would be looking in the presentation for the app.config or web.config – which doesn’t seem right.
In this DAL situation, what is the best way to keep the concrete DataContext specification contained in the DAL layer, without having to rebuild each time it is changed? Or even in a broader sense, the best way to keep configuration external in the DAL layer?
I would try and keep the configuration separate and actually inject it into the layer in question. So in your DAL layer I would perhaps have a factory class that dealt out the particular data gateways and this factory would take an IDataAccessConfiguration parameter in its default constructor. Then you could set static properties in a local configuration class or pass a local copy of the interface into a context when creating it. Example :
Then, when you actually want to get the settings from the particular app.config file you can do it in the standard manner, create a concrete class that implements IDataAccessConfiguration and set its members with the values from the config file and pass that class around. See this link for a question I asked that relates to this : Best way of injecting application configuration
Is this the sort of thing you are looking for?