细节:
我有一个变量,我们称之为CompanyName,它驻留在数据库中,并且几乎每个页面都使用它.每次我需要显示CompanyName时,我都不想访问数据库. 100年前,我会设置Application [“CompanyName”] = CompanyName,但我知道这不是在.NET Core中做事的方法.可以选择什么?
解决方法
AspNetCore有replaced the caching mechanism of ASP.NET并且它对DI友好,但它仍然非常类似于ASP.NET中的状态.主要区别在于您现在需要注入它而不是使用静态HttpContext.Current.Cache属性.
在启动时注册缓存…
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddMvc(); } public void Configure(IApplicationBuilder app) { app.UseMvcWithDefaultRoute(); } }
你可以像…那样注入它
public class HomeController : Controller { private IMemoryCache _cache; public HomeController(IMemoryCache memoryCache) { _cache = memoryCache; } public IActionResult Index() { string companyName = _cache[CacheKeys.CompanyName] as string; return View(); }
然后为了使它在应用程序范围内工作,您可以使用filter或middleware结合某种缓存刷新模式:
>尝试从缓存中获取值
>如果尝试失败
>查找数据库中的数据
>重新填充缓存
>返回值
public string GetCompanyName() { string result; // Look for cache key. if (!_cache.TryGetValue(CacheKeys.CompanyName,out result)) { // Key not in cache,so get data. result = // Lookup data from db // Set cache options. var cacheEntryOptions = new MemoryCacheEntryOptions() // Keep in cache for this time,reset time if accessed. .SetSlidingExpiration(TimeSpan.FromMinutes(60)); // Save data in cache. _cache.Set(CacheKeys.CompanyName,result,cacheEntryOptions); } return result; }
当然,您可以清理它并使用强类型属性创建服务作为注入控制器的缓存的包装器,但这是一般的想法.
另请注意,如果要在Web服务器之间共享数据,则需要使用distributed cache.
You could alternatively use a static method or a statically registered class instance,but do note if hosting on IIS that the static will go out of scope every time the application pool recycles. So,to make that work,you would need to ensure your data is re-populated using a similar refresh pattern.
The primary difference is that with caching there are timeout settings which can be used to optimize how long the data should be stored in the cache (either a hard time limit or a sliding expiration).