【发布时间】:2021-10-06 03:51:35
【问题描述】:
在使用经典 ADO.NET 时,我们通常会在执行完 SQL 命令后立即关闭 SQL 连接,因此连接会关闭并返回到池中。
类似:
public Order[] GetActiveOrders()
{
var orders = new List<Orders>();
using (SqlConnection connection = new SqlConnection("connectionString"))
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "Select * FROM ORDERS WHERE Status = 'Active'";
cmd.Connection.Open();
using (var reader = cmd.ExecuteReader())
{
//populate orders
}
}
}
// SQL connection is closed here and returned back to connection pool
return orders;
}
在使用 EF Core 的 ASP.NET Core 中,我们通常使用 DI 框架将DbContext 注入到构造函数中
public class OrderService:IDisposable
{
private readonly MyDBContext _dbContext;
public OrderService(MyDBContext dbContext)
{
_dbContext = dbContext;
}
public Order[] GetActiveOrders()
{
var orders = _dbContext.Orders.Where(x=>x.Status == 'Active').ToArray()
return orders;
}
#region Dispose
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_dbContext != null)
{
_dbContext.Dispose();
}
// Free any other managed objects here.
}
// Free any unmanaged objects here.
_disposed = true;
}
}
我假设在后台,DbContext 仍在使用SqlCommand 和SqlConnection 连接到数据库。
我想知道 EF Core 什么时候关闭SqlConnection?它会在执行完查询后立即关闭连接(就像我们在经典 ADO 中所做的那样)还是在释放 DbContext 时关闭连接?
那么在上面的例子中,它会在GetActiveOrders()方法返回Orders之前或者当OrderService被DI容器释放时释放连接?
【问题讨论】:
-
一般服务不应该释放它不拥有的资源,即通过ctor注入的任何依赖。
标签: c# asp.net-core entity-framework-core dbcontext sqlconnection