I am making an app which supports multiple databases. The beerhouse architecture instantiates the correct class from the correct provider using the singleton below.
static private ArticlesProvider _instance = null;
static public ArticlesProvider Instance
{
get
{
if (_instance == null)
_instance = (ArticlesProvider)Activator.CreateInstance(
Type.GetType(Globals.Settings.Articles.ProviderType));
return _instance;
}
}
I have the providertype stored into a custom section in my web.config and am trying to create a factory which instantiates the correct DAL class based on the set provider.
The above currently takes the whole namespace stored in the web.config, to the relevant DAL class and is a bit limited as it only creates instances of the ArticlesProvider. How can I make a generic factory, so I can pass in the providertype eg SqlServer and any class eg ArticleDAL, which I wish to instantiate?
Thank you in advance.
I would look into using a proper dependency injection framework, personally I like NInject. This will give you all the tools you need to break the dependency between your application and the underlying database.
You register mappings with the framework, from interfaces to concrete types. These mappings could be in web.config, or in some configuration code in your application startup. The framework will instantiate the classes for you – injecting further dependencies if required.
So you can ask for an instance of IArticleDAL, and if IArticleDAL requires an instance of IDbConnection to access a DB then NInject will automatically create one and pass it to the constructor of the implementation of IArticleDAL.
Anyway – the documentation explains it much better… but in summary the code you’ve extracted above is just a primitive starting point for proper dependency injection.