Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceStack MemoryCacheClient not Caching

I am a relative noob when it comes to ServiceStack and have inherited a project which appears to be trying to make use of the MemoryCacheClient but it seems that no caching appears to take place beyond the scope of a single request e.g. the cache is not persisted between requests, regardless of what expiry I add.

Is that expected? Here is the ICacheManager implementation:

public class CacheManager : ICacheManager
{
    public CacheManager(ICacheClient cacheClient)
    {
        CacheClient = cacheClient;
    }

    public void Clear(IEnumerable<string> cacheKeys)
    {
        Clear(cacheKeys.ToArray());
    }

    public void Clear(params string[] cacheKeys)
    {
        CacheClient.ClearCaches(cacheKeys.ToArray());
    }

    public ICacheClient CacheClient { get; private set; }

    public T Resolve<T>(string cacheKey, Func<T> createCacheFn) where T : class
    {
        return Resolve(cacheKey, new TimeSpan(0, 15, 0), createCacheFn);
    }

    public T Resolve<T>(string cacheKey, TimeSpan expireIn, Func<T> createCacheFn) where T : class
    {
      var cacheResult = CacheClient.Get<T>(cacheKey);
      if (cacheResult != null)
        return cacheResult;

        var item = createCacheFn();
        CacheClient.Set(cacheKey, item, expireIn);
        return item;
    }
}

This is wired up using the AutoFac ContainerBuilder as follows:

_builder.Register(c => new MemoryCacheClient())
    .As<ServiceStack.CacheAccess.ICacheClient>();

_builder.RegisterType<CacheManager>()
    .As<ServiceStack.CacheAccess.ICacheManager>();
like image 808
ProNotion Avatar asked Jul 21 '26 08:07

ProNotion


1 Answers

The MemoryCacheClient instance have to be unique. So you have to tell Autofac to create only a single instance :

_builder.Register(c => new MemoryCacheClient())
        .As<ServiceStack.CacheAccess.ICacheClient>()
        .SingleInstance();

When you don't specify the instance scope mode, Autofac uses instancePerDependency : a new instance will be returned each time you resolve it. See instance scope documentation for more information about instance scope.

like image 162
Cyril Durand Avatar answered Jul 24 '26 01:07

Cyril Durand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!