Caching helps your application’s throughput, Fanray uses IDistributedCache in its domain tier to achieve max flexibility and reuse. Here is an example to retrive a list of blog categories and you see this usage pattern throughout

public async Task<List<Category>> GetAllAsync()
    return await cache.GetAsync(BlogCache.KEY_ALL_CATS, BlogCache.Time_AllCats, async () => {
        return await categoryRepository.GetListAsync();

The above code will

  1. check if blog categories are in the cache, if yes then return them from cache
  2. if not, call the repository and get them from database
  3. after that put the categories into the cache, before returning them

This code is from blog app’s CategoryService. The cache is an instance of IDistributedCache injected through the CategoryService’s constructor, the GetAsync method on the cache is an extension method. KEY_ALL_CATS is the cache key, a const string. Time_AllCats is the cache duration, a static readonly TimeSpan. The categoryRepository is the ICategoryRepository used to retrieve the categories.

A couple things to note

  • most of the cache durations are defaulted to 10 minutes, you can fine tune this based on your need.
  • most frequently requested resources are cached, less requested ones are not, for example only the first page of blog posts is cached