我想知道,在请求完成后,处理所有IDisposable对象的最佳方法是什么。
SQL连接在请求结束后是否被释放,还是我需要继续使用“using”?
AddTransient<T>
- 添加一个类型,每次请求时都会重新创建。AddScoped<T>
- 添加一个类型,保留请求的范围。AddSingleton<T>
- 添加一个类型,当第一次请求时就会创建并保持它。
因此,单例可能不是一个好选择,因为它在应用程序关闭后将被处理。但作用域和瞬态是很好的选择。我有一个存储库,我想像这样创建与我的数据库连接:
public class Dapperr : IDapper
{
private readonly IConfiguration _config;
private string Connectionstring = "DefaultConnection";
public Dapperr(IConfiguration config)
{
_config = config;
}
public void Dispose()
{
}
public T Get<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)
{
using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));
return db.Query<T>(sp, parms, commandType: commandType).FirstOrDefault();
}
public List<T> GetAll<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)
{
using IDbConnection db = new SqlConnection(_config.GetConnectionString(Connectionstring));
return db.Query<T>(sp, parms, commandType: commandType).ToList();
}
}
现在我要在我的创业公司中添加依赖注入:
services.AddScoped<IDapper, Dapperr>();
我想知道如果我添加了作用域依赖,是否可以删除所有这些using
作用域?例如:
public class Dapperr : IDapper
{
private readonly IConfiguration _config;
private string Connectionstring = "DefaultConnection";
private readonly IDbConnection db ;
public Dapperr(IConfiguration config)
{
_config = config;
db = new SqlConnection(_config.GetConnectionString(Connectionstring));
}
public T Get<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.Text)
{
return db.Query<T>(sp, parms, commandType: commandType).FirstOrDefault();
}
public List<T> GetAll<T>(string sp, DynamicParameters parms, CommandType commandType = CommandType.StoredProcedure)
{
return db.Query<T>(sp, parms, commandType: commandType).ToList();
}
}
SQL连接在请求结束后是否被释放,还是我需要继续使用“using”?
IDisposable
接口,并根据释放模式清理资源。依赖注入框架会识别你的类实现了该接口,并在作用域关闭时调用Dispose()
方法。 - OliverDataContext
被注入到DatingRepository
中,并由DI容器管理。这就是为什么如果它实现了IDisposable
,DI容器将处理DataContext
的释放。在您的问题中,SqlConnection
不受DI容器管理,而是由您在代码中手动创建。 - Steven