How to cache a request in ASP.net core

My old code is as follows:

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 do not have the HttpContext more easily accessible in the kernel, how can I achieve the same?

I need to easily access CurrentDb() from outside

I would like to use something like MemoryCache, but with Request lifetime. DI is not an option for this project

+8
c # caching asp.net-core asp.net-core-mvc
source share
2 answers

1. Dependency Injection

You can completely reverse engineer this code: use the built-in DI and register the Database instance as cloud-based (for each web request) using the factory method:

 public void ConfigureServices(IServiceCollection services) { services.AddScoped<Database>((provider) => { return new DatabaseWithMVCMiniProfiler("MainConnectionString"); }); } 

Introduction to Dependency Injection in ASP.NET Kernel

.NET Explain the Life Cycles of a Base Dependency

2. HttpContext.Items

Docs :

This collection is available from the very beginning of HttpRequest and is discarded at the end of each request.

3. AsyncLocal <T>

Save the value for the current asynchronous context (view [ThreadStatic] with async support). This is HttpContext : HttpContextAccessor is stored .

What is the effect of AsyncLocal <T> in non async / await code?

ThreadStatic in ASP.NET Asynchronous Web Interface

+6
source share

Will the database or connection string be the same queries?

If so, you can do it with a static variable and middleware.

The tool will check and set information for each request run, and a static variable will store this value, after which your method could read it from a static variable.

Another simpler approach would be to enter / pass an IHttpContextAccessor parameter as a parameter. With this you can do with minimal changes, but you have an IHttpContextAccessor pass from each invocation method.

+1
source share

All Articles