如何在ASP.net Core中按请求缓存 [英] How to Per-Request caching in ASP.net core

查看:152
本文介绍了如何在ASP.net Core中按请求缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的旧代码如下:

    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,因此我该如何实现同一目标?

Since we don't have HttpContext anymore easily accesible in core, how can I achieve the same thing?

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

I need to access CurrentDb() easily from everywhere

想使用诸如MemoryCache之类的东西,但是具有请求生存期. DI这不是该项目的选择

推荐答案

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

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

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

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<Database>((provider) =>
    {
        return new DatabaseWithMVCMiniProfiler("MainConnectionString");
    });
}

ASP.NET Core中的依赖注入简介

.net核心依赖项注入寿命说明

此集合从HttpRequest的开始就可用,并且在每个请求的末尾都将被丢弃.

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

使用HttpContext.项目

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

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

AsyncLocal的影响是什么?在非异步/等待代码中?

异步ASP.NET Web API中的ThreadStatic

这篇关于如何在ASP.net Core中按请求缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆