How to Per-Request caching in ASP.net core

做~自己de王妃 提交于 2019-12-05 15:26:02

问题


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?

I need to access CurrentDb() easily from everywhere

Would like to use something like MemoryCache, but with Request lifetime. DI it's not an option for this project


回答1:


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

1. Dependency Injection

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

Introduction to Dependency Injection in ASP.NET Core

.net Core Dependency Injection Lifetimes Explained

2. HttpContext.Items

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

Working with HttpContext.Items

3. AsyncLocal<T>

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

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

ThreadStatic in asynchronous ASP.NET Web API




回答2:


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. With this you could do with minimal changes but you have the pass the IHttpContextAccessor service from each calling method.



来源:https://stackoverflow.com/questions/44348310/how-to-per-request-caching-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!