How to Per-Request caching in ASP.net core

后端 未结 2 1133
礼貌的吻别
礼貌的吻别 2021-02-19 05:04

My old code looks like this:

    public static class DbHelper {
        // One conection per request
        public static         


        
2条回答
  •  佛祖请我去吃肉
    2021-02-19 05:31

    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 build-in DI and register a Database instance as scoped (per web-request) with the following factory method:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped((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

    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 in non async/await code?

    ThreadStatic in asynchronous ASP.NET Web API

提交回复
热议问题