Skip to content
njy edited this page Apr 17, 2019 · 10 revisions

NOTE: This quickstart is for LazyCache version 2.x

Using Lazycache without dependency injection

Add LazyCache to your project

dotnet add MyProject package LazyCache

Create a cache an use it:

//Create my cache manually
IAppCache cache = new CachingService();

// define a func to get the products but do not Execute() it
Func<IEnumerable<Product>> productGetter = () => dbContext.Products.ToList();

// Either 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);

// use the cached results
System.Console.WriteLine($"Found {productsWithCaching.Count} products");

Using LazyCache.AspNetCore and Microsoft.Extensions.DependencyInjection

LazyCache is designed for dependency injection and has support for the IoC container Microsoft.Extensions.DependencyInjection in the LazyCache.AspNetCore project. Add LazyCache.AspNetCore to your project (LazyCache.AspNetCore has a dependency on LazyCache so that will get installed automatically if not already)

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 implementation
    // 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 HomeController(ProductDbContext dbContext, IAppCache cache)
    {
        this.dbContext = dbContext;
        this.cache = cache;
    }

Wrap the call you want to cache in a lambda 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;
}