Asp.Net Core: Use memory cache outside controller

前端 未结 3 514
轻奢々
轻奢々 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: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();
    }
    

    and declare IMemoryCache as dependency in ScheduledStuff constructor:

    public class ScheduledStuff {
      IMemoryCache MemCache;
      public ScheduledStuff(IMemoryCache memCache) {
        MemCache = memCache;
      }
    }
    

提交回复
热议问题