我們使用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容器應該負責處理上下文,所以編號 –