ServiceStack MemoryCacheClient不缓存

时间:2015-04-08 13:22:20

标签: asp.net-mvc caching servicestack autofac

当谈到ServiceStack时,我是一个相对的noob,并继承了一个似乎试图利用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>();

1 个答案:

答案 0 :(得分:4)

MemoryCacheClient实例必须是唯一的。因此,您必须告诉 Autofac 只创建一个实例:

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

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