My old code looks like this:
public static class DbHelper {
// One conection per request
public static Database CurrentDb() {
if (HttpContext.Current.Items["CurrentDb"] == null) {
var retval = new DatabaseWithMVCMiniProfiler("MainConnectionString");
HttpContext.Current.Items["CurrentDb"] = retval;
return retval;
}
return (Database)HttpContext.Current.Items["CurrentDb"];
}
}
Since we don't have HttpContext anymore easily accesible in core, how can I achieve the same thing?
I need to access CurrentDb()
easily from everywhere
Would like to use something like MemoryCache, but with Request lifetime. DI it's not an option for this project
There are at least 3 options to store an object per-request in ASP.NET Core:
You could totally re-design that old code: use the built-in DI and register a Database
instance as scoped (per web-request) with the following factory method:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<Database>((provider) =>
{
return new DatabaseWithMVCMiniProfiler("MainConnectionString");
});
}
Introduction to Dependency Injection in ASP.NET Core
.NET Core Dependency Injection Lifetimes Explained
This collection is available from the start of an HttpRequest and is discarded at the end of each request.
Working with HttpContext.Items
Store a value per a current async context (a kind of [ThreadStatic]
with async support). This is how HttpContext
is actually stored: HttpContextAccessor.