问题描述
我正在运行带有Entity Framework Core的ASP.NET Core 1.0 Web应用程序。当应用程序运行了一段时间(24-48小时)后,该应用程序在对任何端点或静态资源的每个请求上开始崩溃,并抛出错误 System.InvalidOperationException:ExecuteReader需要打开且可用的Connection。连接的当前状态已关闭。
我只能通过重新启动应用程序池来从中恢复。
I'm running an ASP.NET Core 1.0 web app with Entity Framework Core. When the app has been running for a while (24 - 48 hours), the app starts crashing on every request to any endpoint or static resource throwing the error System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed.
I can only recover from this by restarting the App Pool.
我正在像这样配置实体框架:
I am configuring Entity Framework like this:
Startup.cs
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
我正在使用这样的扩展方法在owin管道中加载数据:
I am loading data in the owin pipeline with an extension method like this like this:
Startup.cs
Startup.cs
app.LoadTenantData();
AppBuilderExtensions.cs:
AppBuilderExtensions.cs:
public static void LoadTenantData(this IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
var dbContext = app.ApplicationServices.GetService<ApplicationDbContext>();
var club = dbContext.Clubs.Single(c => c.Id == GetClubIdFromUrl(context));
context.Items[PipelineConstants.ClubKey] = club;
await next();
});
}
由于错误仅在应用程序已运行很长时间时发生,很难复制,但是我认为它与EF错误地打开和关闭连接有关。
Since the error only occurs when the app has been running for a long time, it is hard to reproduce, but I'm assuming it has something to do with EF opening and closing connections incorrectly.
我该如何调试呢?我使用EF是否不正确?
How can I go about to debug this? Am I using EF incorrectly?
推荐答案
我遇到了同样的问题。
I got same issue.
我认为同一dbcontext实例可能被多个线程同时使用。
I think it is likely that the same dbcontext instance is being used concurrently by multiple threads.
需要这个:
services.AddDbContext< ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString( DefaultConnection)),ServiceLifetime.Transient);
有一个问题。
这篇关于EF核心-System.InvalidOperationException:ExecuteReader需要打开且可用的连接。连接的当前状态为关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!