我们使用ASP.NET实体框架的核心在我们的Web API应用程序查询我们的MSSQL数据库。有时,当我们有很大的流量,查询到DB与此错误结束:EF核心和大流量导致最大池大小达到误差
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
我不知道如果我们使用DbContext
和查询的模式是正确的,或者如果我错过了一些使用/ Dispose模式和错误被一些引起内存泄漏(在我读过一些研究后,我不应该使用,因为生命周期是由框架管理的)。我下面documentation ...
我的connectionString:
"myConnection": "Server=xxx;Database=xxx;user id=xxx;password=xxx;Max Pool Size=200;Timeout=200;"
我Startup.cs
public void ConfigureServices(IServiceCollection services)
{
.....
// scoped context
services.AddDbContext<MyDbContext>(
options => options.UseSqlServer(this.Configuration.GetConnectionString("myConnection")));
}
然后在控制器我用的DbContext的依赖注入:
public class MyController : Controller
public MyController (MyDbContext context)
{
this.Context = context;
}
public ActionResult Get(int id)
{
// querying
return this.Context.tRealty.Where(x=>x.id == id).FirstOrDefault();
}
应该我使用类似于:
using (var context = this.Context)
{
return this.Context.tRealty.Where(x => x.id == id).FirstOrDefault();
}
但我认为这是错误的思路时,我使用的DbContext
依赖注入。
似乎你已经回答了你自己的问题。 –
所以我应该在查询通过依赖注入添加的dbcontext时使用__using__ ... –
DI容器应该负责处理上下文,所以编号 –