简体   繁体   English

如何在 ASP.net 核心中按请求缓存

[英]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?由于我们在核心中不再有 HttpContext 容易访问,我怎样才能实现同样的事情?

I need to access CurrentDb() easily from everywhere我需要从任何地方轻松访问CurrentDb()

Would like to use something like MemoryCache, but with Request lifetime.想使用类似 MemoryCache 的东西,但有请求生命周期。 DI it's not an option for this project DI 这不是这个项目的一个选项

There are at least 3 options to store an object per-request in ASP.NET Core:至少有 3 个选项可以在 ASP.NET Core 中存储每个请求的对象:

1. Dependency Injection 1. 依赖注入

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:您可以完全重新设计旧代码:使用内置 DI 并使用以下工厂方法将Database实例注册为作用域(每个 Web 请求):

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

Introduction to Dependency Injection in ASP.NET Core ASP.NET Core 中的依赖注入简介

.NET Core Dependency Injection Lifetimes Explained .NET Core 依赖注入生命周期解释

2. HttpContext.Items 2. HttpContext.Items

This collection is available from the start of an HttpRequest and is discarded at the end of each request.该集合在 HttpRequest 开始时可用,并在每个请求结束时被丢弃。

Working with HttpContext.Items 使用 HttpContext.Items

3. AsyncLocal<T> 3. 异步本地<T>

Store a value per a current async context (a kind of [ThreadStatic] with async support).每个当前异步上下文存储一个值(一种具有异步支持的[ThreadStatic] )。 This is how HttpContext is actually stored: HttpContextAccessor .这就是HttpContext的实际存储方式: HttpContextAccessor

What's the effect of AsyncLocal<T> in non async/await code? AsyncLocal<T> 在非 async/await 代码中的作用是什么?

ThreadStatic in asynchronous ASP.NET Web API 异步 ASP.NET Web API 中的 ThreadStatic

Will not the database or connection string would be same across the requests?请求中的数据库或连接字符串不会相同吗?

If so then you could do it by a static variable and middleware.如果是这样,那么您可以通过静态变量和中间件来完成。

The middleware would check and set the info on each request start and static variable would store the value then your method could read it from the static variable.中间件将检查并设置每个请求开始的信息,静态变量将存储该值,然后您的方法可以从静态变量中读取它。

Other simpler approach would be to inject/pass the IHttpContextAccessor as parameter.其他更简单的方法是将 IHttpContextAccessor 作为参数注入/传递。 With this you could do with minimal changes but you have the pass the IHttpContextAccessor service from each calling method.有了这个,您可以做最少的更改,但是您可以从每个调用方法传递 IHttpContextAccessor 服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM