Archief

Dev

Speeding up Orchard: Working with the CacheManager

Caching can be a really nice solution if you’ve got some heavy queries, webservice calls or other stuff that takes a long time. Orchard has a nice, but different, cachemanager inside.

Let’s first have a look at how you can set it up in your project. I’m using the PackageUpdateService that comes in the Orchard.Packaging module as an example.

private readonly ICacheManager _cacheManager;
private readonly IClock _clock;
private readonly ISignals _signals;

public PackageUpdateService(
    ICacheManager cacheManager,
    IClock clock,
    ISignals signals)
{
  _cacheManager = cacheManager;
  _clock = clock;
  _signals = signals;
}

This is a simplified version, but these three elements are needed to get caching going. Now to get something from cache:

public PackagesStatusResult GetPackages(PackagingSource packagingSource)
{
  // Refresh every 23 hours or when signal was triggered
  return _cacheManager.Get("UniqueKey", ctx =>
  {
    ctx.Monitor(_clock.When(TimeSpan.FromMinutes(60 * 23)));
    ctx.Monitor(_signals.When("PackageUpdateService"));

    return GetPackagesWorker(packagingSource);
  });
}

The Get function is a generic, so it just returns the type of object that the function itself returns. This is common for most caching solutions. The magic is with the Monitor functions, which you can pass an IVolatileToken. There are currently two implementations of IVolatileProvider: IClock and ISignals. As you can see in the code above, the clock can invalidate the cache after a specific timespan. 

The signals have a When and a Trigger function. The Trigger function will invalidate any caches that have been set with an object with the same value in the When function.

Enjoy!

#orchard #performance #cache