Hi i have this class to instantiate DAL classes:
public class Factory
{
public static T GetInstance<T>() where T : new()
{
return new T();
}
}
I want to make my application capable of using multiple databases. I was planning on setting the database in my web.config and then pass in that setting possibly to the factory class where it will return the correct DAL class. I think my methodology is ok im just a bit stuck on how to implement it whilst keeping it generic.
Maybe something like this:
public class Factory
{
private static readonly string dbType = ConfigurationSettings.Appsettings["SqlServer"];
public static T GetInstance<T>() where T : new()
{
switch(dbType)
{
case "SqlServer":
return new T(); //Not sure what to put here.
break;
case: "MySql":
return new T();
break;
default: "No datasource";
}
}
}
If anyone could help or point me in the right direction that would be great.
Thanks in advance.
You should look at the System.Data.Common NameSpace. This namespace uses structures like DbConnection, DbReader, and so on, and itself uses a factory method to great the required DbProvider.
So instead of going down your current path, I would suggest letting the current .net data framework do the lifting for you.
here’s a quick example.
The GetFactory call can accept any Provider that installed on the machine, Oracle, MySql, Sql, etc.
You can also Get all providers that are installed on a machine by making a call to static DataTable GetFactoryClasses() this returns a datatable object.
The idea behind this would be to avoid provider specific implementations and rely on a generic implementation that would accommodate all your needs.
Writing Provider Independent Code in ADO.NET
I hope that you find this helpful.