c# - 如何在 ASP.net Core 中进行 Per-Request 缓存

标签 c# caching asp.net-core asp.net-core-mvc

我的旧代码是这样的:

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"];
    }
}

既然我们不再有 HttpContext 在核心中很容易访问,我怎样才能达到同样的目的?

我需要从任何地方轻松访问 CurrentDb()

想要使用 MemoryCache 之类的东西,但有 Request 生命周期。 DI 这不是这个项目的选项

最佳答案

在 ASP.NET Core 中至少有 3 个选项来存储每个请求的对象:

1.依赖注入(inject)

您完全可以重新设计旧代码:使用内置 DI 并使用以下工厂方法将 Database 实例注册为作用域(根据网络请求):

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

此集合在 HttpRequest 开始时可用,并在每个请求结束时丢弃。

Working with HttpContext.Items

3。异步本地

为每个当前异步上下文存储一个值(一种具有异步支持的[ThreadStatic])。这是 HttpContext 实际存储的方式:HttpContextAccessor .

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

ThreadStatic in asynchronous ASP.NET Web API

关于c# - 如何在 ASP.net Core 中进行 Per-Request 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44348310/

相关文章:

c# - 不为同步请求调用中间件

c# - 在控制台应用程序中启动 WPF 应用程序

asp.net-mvc - ASP.NET MVC 响应过滤器 + OutputCache 属性

html - 远程清除IE缓存

c# - Xamarin/Mvvmcross : Open a different view controller when a iOS push notification is received

c# - Html 敏捷包 Xpath

ruby - 为散列生成缓存键(唯一键)

c# - 从路由名称获取相对路径

c# - AspNetCore项目仅在Linux容器上提供System.IO.FileNotFoundException

c# - 处理抛出 Controller 方法参数的构造函数?