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

编程入门 行业动态 更新时间:2024-10-26 07:36:32
本文介绍了如何在ASP 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中的依赖注入简介

核心依赖项注入寿命说明

此集合从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中按请求缓存

本文发布于:2023-11-13 21:44:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585400.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   如何在   net   ASP   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!