I am trying to maintain a single connection per request in my web application.
On the first attempt to connect to the database each request I create a new instance of the connection and store it in HttpContext.Current.Items
, which works great in a traditional web application, however this all falls apart when I use async await.
The issue is that httpContact.Current
returns null when called from an async method, (I am guessing this is because current is tied into the original thread?).
Is there an alternative which will allow my to create and dispose my connection per request and still work when using async await?
Edit: Code sample as requested
public static DatabaseContext Context
{
get
{
if (HttpContext.Current.Items.Contains(DbContextKey))
{
return (DatabaseContext)HttpContext.Current.Items[DbContextKey];
}
var context = new DatabaseContext();
HttpContext.Current.Items.Add(DbContextKey, context);
return context;
}
}