我从我的 micro Orm 粘贴此代码。构造函数有多个重载来指定要使用的 Db。
public class DbAccess : IDisposable
{
public DbAccess()
{
var cnx=ConfigurationManager.ConnectionStrings[0];
if (cnx==null) throw new InvalidOperationException("I need a connection!!!");
Init(cnx.ConnectionString,ProviderFactory.GetProviderByName(cnx.ProviderName));
}
public DbAccess(string connectionStringName)
{
var cnx = ConfigurationManager.ConnectionStrings[connectionStringName];
if (cnx == null) throw new InvalidOperationException("I need a connection!!!");
Init(cnx.ConnectionString, ProviderFactory.GetProviderByName(cnx.ProviderName));
}
public DbAccess(string cnxString,string provider)
{
Init(cnxString,ProviderFactory.GetProviderByName(provider));
}
public DbAccess(string cnxString,DBType provider)
{
Init(cnxString,ProviderFactory.GetProvider(provider));
}
public DbAccess(string cnxString,IHaveDbProvider provider)
{
Init(cnxString, provider);
} //other stuff
}
请注意,DAO (DbAccess) 并不关心具体的提供者。这是 ProviderFactory 的外观。在这里,您可以添加一种方法来检测数据库并返回提供程序。
internal static class ProviderFactory
{
public static IHaveDbProvider GetProviderByName(string providerName)
{
switch (providerName)
{
case SqlServerProvider.ProviderName:return new SqlServerProvider();
case MySqlProvider.ProviderName:return new MySqlProvider();
case PostgresProvider.ProviderName:return new PostgresProvider();
case OracleProvider.ProviderName:return new OracleProvider();
case SqlServerCEProvider.ProviderName:return new SqlServerCEProvider();
case SqliteProvider.ProviderName:return new SqliteProvider();
}
throw new Exception("Unkown provider");
}
public static IHaveDbProvider GetProvider(DBType type)
{
switch (type)
{
case DBType.SqlServer: return new SqlServerProvider();
case DBType.SqlServerCE: return new SqlServerCEProvider();
case DBType.MySql: return new MySqlProvider();
case DBType.PostgreSQL:return new PostgresProvider();
case DBType.Oracle:return new OracleProvider();
case DBType.SQLite:return new SqliteProvider();
}
throw new Exception("Unkown provider");
}
}
有关更多代码片段和灵感,您可以查看Github 存储库
我建议不要使用单例模式,让 DI 容器来管理实例生命周期要好得多。此外,应用程序应该使用 DAO 的接口而不是具体实例(这将在未来帮助您)。