Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Per-Request caching in ASP.net core

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

like image 959
Eduardo Molteni Avatar asked Jun 03 '17 20:06

Eduardo Molteni


People also ask

How many requests per second can ASP.NET Core handle?

7+ Million HTTP requests per second from a single server.

How do I cache data in .NET Core?

ASP.NET Core supports several different caches. The simplest cache is based on the IMemoryCache. IMemoryCache represents a cache stored in the memory of the web server. Apps running on a server farm (multiple servers) should ensure sessions are sticky when using the in-memory cache.

How does ASP.NET Core handle multiple requests?

ASP.NET Core apps should be designed to process many requests simultaneously. Asynchronous APIs allow a small pool of threads to handle thousands of concurrent requests by not waiting on blocking calls. Rather than waiting on a long-running synchronous task to complete, the thread can work on another request.


1 Answers

There are at least 3 options to store an object per-request in ASP.NET Core:

1. Dependency Injection

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

2. HttpContext.Items

This collection is available from the start of an HttpRequest and is discarded at the end of each request.

Working with HttpContext.Items

3. AsyncLocal<T>

Store a value per a current async context (a kind of [ThreadStatic] with async support). This is how HttpContext is actually stored: HttpContextAccessor.

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

ThreadStatic in asynchronous ASP.NET Web API

like image 80
Ilya Chumakov Avatar answered Oct 19 '22 22:10

Ilya Chumakov