问:


下面的代码,在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:

  1. public class Startup
  2. {
  3. public Startup(IHostingEnvironment env)
  4. {
  5. //Startup stuff
  6. }
  7.  
  8. public void ConfigureServices(IServiceCollection services)
  9. {
  10. //configure other services
  11.  
  12. services.AddMemoryCache();
  13.  
  14. var cache = new MemoryCache(new MemoryCacheOptions());
  15. var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
  16.  
  17. //Some examples of me putting data in the cache
  18. cache.Set("entryA", "data1", entryOptions);
  19. cache.Set("entryB", data2, entryOptions);
  20. cache.Set("entryC", data3.Keys.ToList(), entryOptions);
  21. }
  22.  
  23. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  24. {
  25. //pipeline configuration
  26. }
  27. }

And the Controller where I use the MemoryCache

  1. public class ExampleController : Controller
  2. {
  3. private readonly IMemoryCache _cache;
  4.  
  5. public ExampleController(IMemoryCache cache)
  6. {
  7. _cache = cache;
  8. }
  9.  
  10. [HttpGet]
  11. public IActionResult Index()
  12. {
  13. //At this point, I have a different MemoryCache instance.
  14. ViewData["CachedData"] = _cache.Get("entryA");//这里"entryA"从IMemoryCache中找不到,为null
  15.  
  16. return View();
  17. }
  18. }

答:


When you added the statement

  1. 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:

  1. public void Configure(IApplicationBuilder app,
  2. IHostingEnvironment env,
  3. ILoggerFactory loggerFactory,
  4. IMemoryCache cache )
  5. {
  6. var entryOptions = new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove);
  7.  
  8. //Some examples of me putting data in the cache
  9. cache.Set("entryA", "data1", entryOptions);
  10. cache.Set("entryB", data2, entryOptions);
  11. cache.Set("entryC", data3.Keys.ToList(), entryOptions);
  12. //pipeline configuration
  13. }

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参数:

  1. public class UserProfileMiddleware
  2. {
  3. private readonly RequestDelegate next;
  4. private readonly IMemoryCache cache;
  5.  
  6. public UserProfileMiddleware(
  7. RequestDelegate next,
  8. IMemoryCache cache)
  9. {
  10. this.next = next;
  11. this.cache = cache;
  12. }
  13.  
  14. public async Task Invoke(
  15. Microsoft.AspNetCore.Http.HttpContext context)
  16. {
  17. if (UserProfile.cache == null)
  18. {
  19. UserProfile.cache = cache;
  20. }
  21.  
  22. await next.Invoke(context);
  23. }
  24. }

原文链接

在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. 7、srpingboot改变JDK版本

    在pom.xml中加上 <plugin> <artifactId>maven-compiler-plugin</artifactId> <configurat ...

  2. 【转】JSON.parse()与JSON.stringify()的区别

    JSON.parse()[从一个字符串中解析出json对象] 例子: //定义一个字符串 var data='{"name":"goatling"}' //解析 ...

  3. 洛谷P1600 天天爱跑步(差分 LCA 桶)

    题意 题目链接 Sol 一步一步的来考虑 \(25 \%\):直接\(O(nm)\)的暴力 链的情况:维护两个差分数组,分别表示从左向右和从右向左的贡献, \(S_i = 1\):统计每个点的子树内有 ...

  4. web前端开发需要具备的技能

    web前端开发需要具备以下7种技能: 1.页面标记(HTML) HTML页面固定,标签不多,相对来说学起来比较容易.编写HTML代码需遵循HTML代码规范(http://www.cnblogs.com ...

  5. python(day1-11)

    day1:Python入门 day2:数字类型字符编码 day3:函数 day4:模块与包 day5:常用模块 day6:面向对象 day8:异常处理 day9:网络编程 day10:并发编程 day ...

  6. Mysql 优化配置2

    服务器物理硬件的优化 来源社区,个人作为收集 在挑选硬件服务器时,我们应该从下面几个方面着重对MySQL服务器的硬件配置进行优化,也就是说将项目中的资金着重投入到如下几处: 1.磁盘寻道能力(磁盘I/ ...

  7. DevExpress GridControl如何取消默认的显示方式

    DevExpress GridControl如何取消默认的显示方式,就是表格中好像还嵌套了一个表格,下面有个折叠‘+’按钮,我需要显示的是就是单表格的样式效果. 默认的样式如图: 我需要显示的效果图: ...

  8. 【Leetcode】【Medium】Convert Sorted Array to Binary Search Tree

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 解题 ...

  9. Thread.Join()的详解

    什么是进程?当一个程序开始运行时,它就是一个进程,进程包括运行中的程序和程序所使用到的内存和系统资源.而一个进程又是由多个线程所组成的. 什么是线程?线程是程序中的一个执行流,每个线程都有自己的专有寄 ...

  10. Hadoop学习---Hadoop的HBase的学习

    Hbase Hbase的特点: Hbase是bigtable的开源的仿制版本 建立在HDFS之上 可靠性,靠性能 大:一个表可以有上亿行,上百万列 面向列:面向列(族)的存储和权限控制,列(族)独立检 ...