问题描述
我的旧代码如下:
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");
});
}
此集合从HttpRequest的开始就可用,并且在每个请求的末尾都将被丢弃.
This collection is available from the start of an HttpRequest and is discarded at the end of each request.
为每个当前异步上下文存储一个值(一种具有异步支持的[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.
异步ASP.NET Web API中的ThreadStatic
这篇关于如何在ASP.net Core中按请求缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!