-
Notifications
You must be signed in to change notification settings - Fork 159
Quickstart
Alastair Crabtree edited this page Mar 4, 2018
·
10 revisions
NOTE: This quickstart is for LazyCache version 2.x
Add LazyCache.AspNetCore to your project (LazyCache.AspNetCore has a dependency on LazyCache so it should get installed automatically)
dotnet add MyProject package LazyCache.AspNetCore
Add the LazyCache services in you aspnet core Startup.cs
// This method gets called by the runtime. Use this method to add services.
public void ConfigureServices(IServiceCollection services)
{
// already existing registrations
services.AddMvc();
services.AddDbContext<MyContext>(options => options.UseSqlServer("some db"));
....
// Register LazyCache - makes the IAppCache impelmentation
// CachingService available to your code
services.AddLazyCache();
}
Take IAppCache as a dependency in the constructor of the class in which you want to use it
public class HomeController : Controller
{
private readonly IAppCache cache;
private readonly ProductDbContext dbContext;
public DbTimeController(ProductDbContext dbContext, IAppCache cache)
{
this.dbContext = dbContext;
this.cache = cache;
}
Wrap the call you want to cache in a lamda and use the cache:
[HttpGet]
[Route("api/products")]
public IEnumerable<Product> Get()
{
// define a func to get the products but do not Execute() it
Func<IEnumerable<Product>> productGetter = () => dbContext.Products.ToList();
// get the results from the cache based on a unique key, or
// execute the func and cache the results
var productsWithCaching = cache.GetOrAdd("HomeController.Get", productGetter);
return productsWithCaching;
}