我的班级有以下核心:
class SmartDbConnection
{
private readonly IDbConnection Connection;
public SmartDbConnection(string ConnectionString)
{
if(ConnectionString.Contains("MultipleActiveResultSets=true"))
{
Connection = new SqlConnection(ConnectionString);
}
}
}
我不希望它有“SqlConnection”硬编码。所以我想把它变成一个Generic类(接受IDbConnection类)。但我不知道该怎么做。有人可以帮忙吗?
答案 0 :(得分:10)
首先 - 我已添加IDisposable
,因为我认为这很重要。
其次,请注意提供商是另一种选择:
class SmartDbConnection
{
private DbConnection Connection;
public SmartDbConnection(string provider, string connectionString)
{
Connection = DbProviderFactories.GetFactory(provider)
.CreateConnection();
Connection.ConnectionString = connectionString;
}
public void Dispose() {
if (Connection != null)
{
Connection.Dispose();
Connection = null;
}
}
}
如果你必须通用,那怎么样:
class SmartDbConnection<T> : IDisposable where T : class,
IDbConnection, new()
{
private T Connection;
public SmartDbConnection(string connectionString)
{
T t = new T();
t.ConnectionString = connectionString;
// etc
}
public void Dispose() {
if (Connection != null)
{
Connection.Dispose();
Connection = null;
}
}
}
答案 1 :(得分:8)
为什么不接受IDbConnection而不是连接到你的ctor?
答案 2 :(得分:2)
也许......
class SmartDbConnection<T> where T : IDbConnection, new()
{
private readonly IDbConnection Connection;
public SmartDbConnection(string connectionString)
{
if (connectionString.Contains("MultipleActiveResultSets=true"))
{
Connection = new T();
Connection.ConnectionString = connectionString;
}
}
}
编辑:但是kaanbardak建议可以更好......
答案 3 :(得分:1)
如果你不想在那里指定SqlConnection,你会在哪里指定它 - 只有当连接字符串包含“MultipleActiveResultSets = true”时你才知道如何使用它?
我怀疑在某种程度上你想要一个连接工厂 - 你可以传入或设置某个Func<string, IDbConnection>
,或者可能只是一个类:
public static class ConnectionFactory
{
public static IDbConnection CreateConnection(string connectionString)
{
// Hard-code stuff here
}
}
当然,它们只是同一枚硬币的两面 - ConnectionFactory只是Func<string, IDbConnection>
的静态实现。
答案 4 :(得分:0)
class SmartDbConnection<T> where T: IDbConnection , new()
{
private readonly T Connection;
public SmartDbConnection(string ConnectionString)
{
if (ConnectionString.Contains("MultipleActiveResultSets=true"))
{
Connection = new T();
Connection.ConnectionString = ConnectionString;
}
}
}