MichaCo / CacheManager

CacheManager is an open source caching abstraction layer for .NET written in C#. It supports various cache providers and implements many advanced features.
http://cachemanager.michaco.net
Apache License 2.0
2.34k stars 457 forks source link

Clearing cache of all types at all levels #255

Closed PaulRReynolds closed 5 years ago

PaulRReynolds commented 5 years ago

I've seen #141 which explains how to use the Clear() method to clear the cache, however what kind of CacheManger should I call this against to clear all cached types?

e.g. in my code I use:

ICacheManager<string> and ICacheManager<Guid>

If I want to clear everything, which ICacheManager<> should I use?

MichaCo commented 5 years ago

Hi @PaulRReynolds That's currently not possible when using separated instances.

CacheManager makes sure to not "share" keys between in-memory cache instances. That's a pretty important feature in most use-cases. If it would share keys, you could, by mistake, use the same key for a string and for a GUID value. That would cause some bad runtime exceptions which will be hard to fix. That's why CacheManager tries to prevent that kind of scenario...

It has the disadvantage though that you cannot clear all instances at once (as you found out).

One way would be to not use different typed instances but one ICacheManager<object> for everything. That would have the disadvantage of non typed usage / casting, and you cannot have different configuration for different types (unless you again create multiple instances)

There is a feature request (see #250) which might be added in a future version, which would allow sharing the cache across multiple instances. That would also allow clearing the cache for all instances. But it would also allow key collisions as described above.

PaulRReynolds commented 5 years ago

Thanks Michael,

I understand the reasoning behind keeping the in-memory caches separate to avoid exceptions due to collisions. The operation to completely clear the cached data is not something I need to do very often, it's purely for occasional maintenance situations where I don't want to restart the App instance to clear the memory cache.

I'm not caching that many different data types (maybe around 10), so an alternative solution I might try is to use a factory which returns an ICacheManager from the container for each of the cached types, and then I can iterate over them and Clear() individually. It's not that pretty, but it will do the job for now.

Thanks for your help!

Paul