内存缓存中的 .NET Core 1.1 web api

.NET Core 1.1 web api in memory caching

我需要使用 .net core web 中的内存缓存选项来缓存一些信息 api。需要在启动时从数据库中获取一些信息并缓存24小时。 API 中的所有控制器都应该从这个缓存中读取数据。 我怎样才能做到这一点?

首先在配置中添加MemoryCache:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddMemoryCache();
}

然后使用程序集提供的 IMemoryCache Microsoft.Extensions.Caching.Memory

public interface IMemoryCache : IDisposable
{
    bool TryGetValue(object key, out object value);
    ICacheEntry CreateEntry(object key);
    void Remove(object key);
}

然后在 类

中的任意位置注入 IMemoryCache
public YourClassConstructor(IMemoryCache cache)
{
   this.cache = cache;
}

您可以像这样设置缓存(例如在您的 BLL 中):

cache.Set(“Key”, DataToCache);

并且在您的控制器中,您可以像这样读取缓存:

[HttpGet()]
public string Get()
{
   return cache.Get<TypeOfYourCachedData>(CacheKey);
}