问:


下面的代码,在ASP.NET Core的startup类中创建了一个MemoryCache并且存储了三个键值“entryA”,“entryB”,“entryC”,之后想在Controller中再把这三个键值从缓存中取出来,但是发现Controller中的构造函数依赖注入的IMemoryCache并不是startup类中的MemoryCache,因为Controller中的IMemoryCache没有任何键值对:

How do I access the MemoryCache instance in Startup that will be used by the rest of my web app? This is how I'm currently trying it:

public class Startup
{
public Startup(IHostingEnvironment env)
{
//Startup stuff
} public void ConfigureServices(IServiceCollection services)
{
//configure other services services.AddMemoryCache(); var cache = new MemoryCache(new MemoryCacheOptions());
var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove); //Some examples of me putting data in the cache
cache.Set("entryA", "data1", entryOptions);
cache.Set("entryB", data2, entryOptions);
cache.Set("entryC", data3.Keys.ToList(), entryOptions);
} public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
//pipeline configuration
}
}

And the Controller where I use the MemoryCache

public class ExampleController : Controller
{
private readonly IMemoryCache _cache; public ExampleController(IMemoryCache cache)
{
_cache = cache;
} [HttpGet]
public IActionResult Index()
{
//At this point, I have a different MemoryCache instance.
ViewData["CachedData"] = _cache.Get("entryA");//这里"entryA"从IMemoryCache中找不到,为null return View();
}
}

答:


When you added the statement

services.AddMemoryCache();

you were in effect saying that you wanted a memory cache singleton that would get resolved wherever you injected IMemoryCache as you did in your controller. So instead of creating a new memory cache, you need to add values to the singleton object that was created. You can do this by changing your Configure method to something like:

public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IMemoryCache cache )
{
var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove); //Some examples of me putting data in the cache
cache.Set("entryA", "data1", entryOptions);
cache.Set("entryB", data2, entryOptions);
cache.Set("entryC", data3.Keys.ToList(), entryOptions);
//pipeline configuration
}

Use Configure method, not ConfigureServices。

意思就是说在ASP.NET Core的startup类中Configure方法是在ConfigureServices方法之后执行的,而如果在ConfigureServices方法中调用了services.AddMemoryCache()来启用MemoryCache的依赖注入,那么就可以在Configure方法的参数中使用IMemoryCache了,ASP.NET Core会自动注入Configure方法的IMemoryCache参数。并且在后续的Controller中注入的也是同一个IMemoryCache参数的实例。

在ConfigureServices方法中调用了services.AddMemoryCache()来启用MemoryCache的依赖注入后,也可以直接在中间件的构造函数中使用IMemoryCache了,ASP.NET Core会自动注入中间件构造函数中的IMemoryCache类型参数(和Configure方法及Controller等地方注入的是同一个实例的MemoryCache,保证了数据的互通)。比如下面代码中我们定义了一个UserProfileMiddleware中间件,其构造函数就有一个IMemoryCache类型的参数cache,当调用UserProfileMiddleware中间件时,ASP.NET Core会自动注入IMemoryCache cache参数:

public class UserProfileMiddleware
{
private readonly RequestDelegate next;
private readonly IMemoryCache cache; public UserProfileMiddleware(
RequestDelegate next,
IMemoryCache cache)
{
this.next = next;
this.cache = cache;
} public async Task Invoke(
Microsoft.AspNetCore.Http.HttpContext context)
{
if (UserProfile.cache == null)
{
UserProfile.cache = cache;
} await next.Invoke(context);
}
}

原文链接

在ASP.NET Core的startup类中如何使用MemoryCache的更多相关文章

  1. ASP.NET Core 3.0 WebApi中使用Swagger生成API文档简介

    参考地址,官网:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/getting-started-with-swashbuckle?view ...

  2. 从ASP.Net Core Web Api模板中移除MVC Razor依赖项

    前言 :本篇文章,我将会介绍如何在不包括MVC / Razor功能和包的情况下,添加最少的依赖项到ASP.NET Core Web API项目中. 一.MVC   VS WebApi (1)在ASP. ...

  3. 理解ASP.NET Core - [01] Startup

    注:本文隶属于<理解ASP.NET Core>系列文章,请查看置顶博客或点击此处查看全文目录 准备工作:一份ASP.NET Core Web API应用程序 当我们来到一个陌生的环境,第一 ...

  4. ASP.Net Core 5.0 MVC 配置文件读取,Startup 类中ConfigureServices 方法、Configure 方法的使用

    配置文件读取 1. 新建FirstController控制器 在appsettings文件内容替换成以下代码 { "Position": { "Title": ...

  5. ASP.NET Core 2 preview 1中Program.cs,Startup.cs和CreateDefaultBuilder的探索

    Exploring Program.cs, Startup.cs and CreateDefaultBuilder in ASP.NET Core 2 preview 1 ASP.NET Core 2 ...

  6. ASP.NET Core 在 JSON 文件中配置依赖注入

    前言 在上一篇文章中写了如何在MVC中配置全局路由前缀,今天给大家介绍一下如何在在 json 文件中配置依赖注入. 在以前的 ASP.NET 4+ (MVC,Web Api,Owin,SingalR等 ...

  7. 跨平台应用集成(在ASP.NET Core MVC 应用程序中集成 Microsoft Graph)

    作者:陈希章 发表于 2017年6月25日 谈一谈.NET 的跨平台 终于要写到这一篇了.跨平台的支持可以说是 Office 365 平台在设计伊始就考虑的目标.我在前面的文章已经提到过了,Micro ...

  8. ASP.NET Core Web API 集成测试中使用 Bearer Token

    在 ASP.NET Core Web API 集成测试一文中, 我介绍了ASP.NET Core Web API的集成测试. 在那里我使用了测试专用的Startup类, 里面的配置和开发时有一些区别, ...

  9. ASP.NET Core MVC应用程序中的后台工作任务

    在应用程序的内存中缓存常见数据(如查找)可以显着提高您的MVC Web应用程序性能和响应时间.当然,这些数据必须定期刷新. 当然你可以使用任何方法来更新数据,例如Redis中就提供了设定缓存对象的生命 ...

随机推荐

  1. JavaScript之如何对客户端进行检测

    本文主要是针对各种客户端进行检测,使用了用户代理字符串检测技术,具体代码如下: var client=function() { var engine= { // 呈现引擎 ie: 0, gecko: ...

  2. UVA 10328(DP,大数,至少连续)

    http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=19825 这道题和http://www.cnblogs.com/qlky/p/ ...

  3. 第1章 初识CSS3

    什么是CSS3? CSS3是CSS2的升级版本,3只是版本号,它在CSS2.1的基础上增加了很多强大的新功能. 目前主流浏览器chrome.safari.firefox.opera.甚至360都已经支 ...

  4. cookie初探——封装和使用cookie(内含彩蛋)

    一.什么是cookie? 页面用来保存信息,如:自动登录.记住用户名 二.cookie的特性1.同一个网站中所有页面共享一套cookie2.数量.大小有限3.有过期时间 三.js中使用cookie d ...

  5. python3在anaconda下安装caffe失败

    Python 跟 Python3 完全就是两种语言 0x00 import caffe FAILED 环境为 Ubuntu 16 cuda 8.0 NVIDIA 361.77 Anaconda2.昨天 ...

  6. 2-5 Sass 的 @ 规则

    @import Sass 支持所有 CSS3 的 @ 规则, 以及一些 Sass 专属的规则,也被称为"指令(directives)". 这些规则在 Sass 中具有不同的功效,详 ...

  7. Creator4.2建模心得与技巧1——树的建立与跟随摄像机旋转

    Creator建模: 树一般在虚拟现实程序中都用面来实现,一种方法是通过两个面相互垂直成90度叠放在一起,另一种方法是让树面正对着视角一起旋转.这里主要说一下第二种方法. 主要思路:把树面一直正对着摄 ...

  8. 【创客+】偷心锁屏创始人Jerry创业心得分享

    偷心锁屏创始人Jerry创业心得分享 作者:Jerry权泉,偷心锁屏创始人 我创业的起因非常偶然.08年在东京早稻田大学读博士期间,每周六都去社区活动中心跟日本人志愿者日语对话练习日语.有一次练习结束 ...

  9. 佛系结对编程---四则运算(Core 第四组)

    ----by core 第四组 ( 邹卫其 范力 ) 一. 项目介绍 1. 能自动生成小学四则运算题目并给出答案,生成题目时可以选择下列参数:   1)生成题目数量   2)每道题目中运算数数量   ...

  10. Xwiki安装部署详解

    一.Xwiki简介XWiki是一个由Java编写的基于LGPL协议发布的开源wiki和应用平台.XWiki是一款基于java所编写的wiki,它可以运行在如Tomcat,Jetty,JBoss,Web ...