Asp.Net Core: Use memory cache outside controller

前端 未结 3 488
轻奢々
轻奢々 2021-01-02 03:14

In ASP.NET Core its very easy to access your memory cache from a controller

In your startup you add:

public void ConfigureServices(IServiceCollection         


        
相关标签:
3条回答
  • 2021-01-02 03:36

    I am bit late here, but just wanted to add a point to save someone's time. You can access IMemoryCache through HttpContext anywhere in application

    var cache = HttpContext.RequestServices.GetService<IMemoryCache>();
    

    Please make sure to add MemeoryCache in Startup

    services.AddMemoryCache();
    
    0 讨论(0)
  • 2021-01-02 03:45

    There is another very flexible and easy way to do it is using System.Runtime.Caching/MemoryCache

    System.Runtime.Caching/MemoryCache:
    This is pretty much the same as the old day's ASP.Net MVC's HttpRuntime.Cache. You can use it on ASP.Net CORE without any dependency injection, in any class you want to. This is how to use it:

    // First install 'System.Runtime.Caching' (NuGet package)
    
    // Add a using
    using System.Runtime.Caching;
    
    // To get a value
    var myString = MemoryCache.Default["itemCacheKey"];
    
    // To store a value
    MemoryCache.Default["itemCacheKey"] = myString;
    
    0 讨论(0)
  • 2021-01-02 03:50

    Memory cache instance may be injected to the any component that is controlled by DI container; this means that you need configure ScheduledStuff instance in the ConfigureServices method:

    public void ConfigureServices(IServiceCollection services) {
      services.AddMemoryCache();
      services.AddSingleton<ScheduledStuff>();
    }
    

    and declare IMemoryCache as dependency in ScheduledStuff constructor:

    public class ScheduledStuff {
      IMemoryCache MemCache;
      public ScheduledStuff(IMemoryCache memCache) {
        MemCache = memCache;
      }
    }
    
    0 讨论(0)
提交回复
热议问题