对于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。