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
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
I am loading data in the owin pipeline with an extension method like this like this:
Startup.cs
app.LoadTenantData();
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();
});
}
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.
How can I go about to debug this? Am I using EF incorrectly?
I got same issue.
I think it is likely that the same dbcontext instance is being used concurrently by multiple threads.
You may need this:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")),ServiceLifetime.Transient);
There is a issue about that.
https://github.com/aspnet/EntityFramework/issues/6491
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With