我想知道在这种情况下我的下面的实现是否是处理SQL连接的最有效方法.
我通常知道如果我直接使用SqlConnection,我可以将连接包装在using块中以自动处理它,但在这种情况下,我想保持连接打开并可用于SQLRespository类中的所有方法.
public class SqlRepository : IRepository
{
private readonly string connectionString;
private SqlConnection connection;
public SqlRepository(string connectionString)
{
this.connectionString = connectionString;
connection = new SqlConnection(connectionString);
connection.Open();
}
public void Method_A()
{
// uses the SqlConnection to fetch data
}
public void Method_B()
{
// uses the SqlConnection to fetch data
}
public void Dispose()
{
connection.Dispose();
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
using (IRepository repository = new SqlRepository(connectionString))
{
var item = repository.items;
}
Run Code Online (Sandbox Code Playgroud)
更新 IRepository确实实现了IDisposable
bry*_*mac 11
不要保持连接打开跨越呼叫.你正在打败连接池.
如果您正在使用汇集的连接(如sqlserver),它将进行池化和重用.只需在方法a和b中打开和关闭即可.
您可以争辩说,如果调用者使用一种方法执行您所做的操作就可以调用它.但是如果你在每个工作方法(1)中使用带有sqlconnection的{},代码将更简单,并且(2)你确保池不会被破坏(意味着当其他请求可以使用它时,你可以将池中的项目排除在池外) .
编辑:
根据评论添加伪.
该模式存在问题,因为呼叫者可以这样做.
//pseudo code
using (SqlRepository r)
{
r.MethodA();
// other code here that takes some time. your holding a connection
// out of the pool and being selfish. other threads could have
// used your connection before you get a chance to use it again.
r.MethodB();
} // freed for others here.
Run Code Online (Sandbox Code Playgroud)
这会破坏服务器的可扩展性 - 相信我.我已经看到非常大的系统被这种情况所困扰 - 通常是因为它们跨越了AT侧交易.
更好的模式:
class Repository
{
void MethodA()
{
using (Sqlconnection)
{
// db call
}
}
void MethodB()
{
using (Sqlconnection)
{
// you can even have multiple calls here (roundtrips)
// and start transactions. although that can be problematic
// for other reasons.
}
}
Run Code Online (Sandbox Code Playgroud)
现在,游泳池是最有效的.我意识到问题在于一次性模式 - 是的,你可以做到.但......
我不会让连接跨越存储库的生命周期.