How to change CacheClients at runtime in ServiceStack?

懵懂的女人 提交于 2019-12-12 19:24:36

问题


I'd like (through app/web configuration perhaps) to change the cache client used in my ServiceStack application, during runtime.

For example, I have this currently:

 container.Register<ICacheClient>(new MemoryCacheClient());

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

EDIT:

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());

Then accessing base.Cache within your service will return the most recent ICacheClient that was registered... ie: in the case above, MemoryCacheClient.

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.


回答1:


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

Hope that helps!




回答2:


It seems to me that you'll need more flexibility rather than just a simple registration on the composite root, you can try to implement the composite pattern in your container registration.

steven explains this pattern using simple injector but I think it can be implemented with the IOC provided OOB by SS or any other

I hope that helps



来源:https://stackoverflow.com/questions/18618354/how-to-change-cacheclients-at-runtime-in-servicestack

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!