I’m working on an ASP.NET Core application where I have a DbContext
instance injected via dependency injection. The context is registered as scoped.
However, I’m experiencing an issue where, when making multiple requests in parallel, the queries from the same context seem to be combining or sharing resources, even though a different instance of the context is supposed to be used for each request.
The context is injected in the constructor:
public async Task<DataTable> GetDataTableFromSqlServerByQuery(string sql)
{
DataTable dt = new DataTable();
using (var cmd = context.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = sql;
await context.Database.OpenConnectionAsync();
using (var sqlReader = (SqlDataReader)await cmd.ExecuteReaderAsync())
{
dt.Load(sqlReader);
}
}
return dt;
}
Sometimes it looks like queries from different HTTP requests are combining into one, and when I check using sp_whoisactive
, it shows the second query running for an absurd amount of time (e.g., 100 days), even though it’s a new request.
I’ve checked
- That
DbContext
is registered as scoped, and I have confirmed with logging that each request gets a new instance - I am using
MultipleActiveResultSets=True
in the connection string
Are there any best practices or things I might be missing that I can do to fix this problem?
4