如何在运行时在 ServiceStack 中更改 CacheClients? [英] How to change CacheClients at runtime in ServiceStack?
问题描述
我想(可能通过应用程序/网络配置)在运行时更改我的 ServiceStack 应用程序中使用的缓存客户端.
I'd like (through app/web configuration perhaps) to change the cache client used in my ServiceStack application, during runtime.
例如,我目前有这个:
container.Register<ICacheClient>(new MemoryCacheClient());
我想在运行时将其更改为 Redis ICacheClient 用法.如果我注册了两个容器(一个 Memory 和一个在 Redis 上)会怎样.是否可以在我的服务中通过这样的调用在运行时在容器之间切换:
I'd like at runtime to change this to a Redis ICacheClient usage. What if I had two containers registered (one Memory and on Redis). Is it possible to switch between containers at runtime in a call like this in my service:
public object Get(FooRequest request)
{
string cacheKey = UrnId.CreateWithParts("Foo", "Bar");
return RequestContext.ToOptimizedResultUsingCache(base.Cache, cacheKey, sCacheDuration, () =>
{
return TestRepository.Foos;
});
}
请注意,经过更多研究,如果您注册了多个 ICacheClient:
Note, after more research, if you have more than one ICacheClient registered:
container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379"));
container.Register(c => c.Resolve<IRedisClientsManager>().GetCacheClient());
container.Register<ICacheClient>(new MemoryCacheClient());
然后在您的服务中访问 base.Cache 将返回最近注册的 ICacheClient... 即:在上述情况下,MemoryCacheClient.
Then accessing base.Cache within your service will return the most recent ICacheClient that was registered... ie: in the case above, MemoryCacheClient.
因此,如果能够从服务中访问 Cache 对象,我只需要一种方法来从我注册的缓存中获取特定的 Cache,而我看不到其任何属性.
So with the ability to access the Cache object from within the service, I'd just need a way to get a particular Cache from my registered caches, which I can't see any property for.
推荐答案
执行这样的操作将允许您根据 Web 配置设置向容器注册不同的提供程序:
Doing something like this would allow you to register different providers with the container based on a web config setting:
var redisCacheString = ConfigurationManager.AppSettings["UseRedis"];
var useRedis = false;
if (!bool.TryParse(redisCacheString, out useRedis))
{
container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379"));
container.Register(c => c.Resolve<IRedisClientsManager>().GetCacheClient());
}
else
{
container.Register<ICacheClient>(new MemoryCacheClient());
}
希望有帮助!
这篇关于如何在运行时在 ServiceStack 中更改 CacheClients?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!