2

我的班级有以下核心:

class SmartDbConnection
{
    private readonly IDbConnection Connection;

    public SmartDbConnection(string ConnectionString)
    {
        if(ConnectionString.Contains("MultipleActiveResultSets=true"))
        {
            Connection = new SqlConnection(ConnectionString);
        }
    }
}

我不希望它硬编码“SqlConnection”。所以我想把它变成一个通用类(接受 IDbConnection 类)。但我不知道该怎么做。任何人都可以帮忙吗?

4

5 回答 5

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;
        }
    }
}
于 2009-01-16T14:00:33.893 回答
8

你为什么不接受 IDbConnection 而不是你的ctor的连接字符串?

于 2009-01-16T13:59:19.527 回答
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 的建议可能会更好......

于 2009-01-16T13:59:39.400 回答
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>.

于 2009-01-16T14:00:17.247 回答
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;
      }
    }
  }
于 2009-01-16T14:03:57.753 回答