ServiceStack MemoryCacheClient 不缓存

ServiceStack MemoryCacheClient not Caching

当涉及到 ServiceStack 时,我是一个相对的菜鸟,并且继承了一个似乎试图利用 MemoryCacheClient 的项目,但似乎没有缓存发生在单个请求的范围之外,例如无论我添加什么到期时间,缓存都不会在请求之间保留。

这是预期的吗?这是 ICacheManager 的实现:

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;
    }
}

这是使用 AutoFac ContainerBuilder 连接起来的,如下所示:

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

_builder.RegisterType<CacheManager>()
    .As<ServiceStack.CacheAccess.ICacheManager>();

MemoryCacheClient 实例必须是唯一的。所以你必须告诉 Autofac 只创建一个实例:

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

当你没有指定实例作用域模式时,Autofac 使用 instancePerDependency :每次解析时都会返回一个新实例它。有关实例范围的更多信息,请参阅 instance scope documentation