Marking IMemoryCache entries by tags for easier removing.
Extensions.Caching.Tags is available on NuGet.
dotnet add package Extensions.Caching.Tags
Use registration of service for IMemoryCache
by general way:
using Microsoft.Extensions.DependencyInjection;
//...
services.AddMemoryCache();
After getting service you may add tag or tags for caching entries. Just add it as last parameter:
using Microsoft.Extensions.Caching.Memory; //Use common namespace for caching. No need to add something else
_cache.Set(key, value, optionsOrExpiration, new CacheTags("tag0", "tag1"));
_cache.Set(key, value, optionsOrExpiration, new CacheTags { "tag0", "tag1" }); //Same behaviour as above
_cache.Set(key, value, optionsOrExpiration, new[] {"tag0", "tag1"}); //Same behaviour as above
CacheTags
is inherited class from List<string>
.
After that you can remove entries from cache by this way:
_cache.RemoveByTag("tag0"); //will remove all entries tagged by "tag0"
Contributions to the package are always welcome!
The code base is licensed under the Apache License v2.0.
Some methods of this package are wrappers for methods from Microsoft.Extensions.Caching.Abstractions. Also this package is using namespace Microsoft.Extensions.Caching.Memory for easier use.
See Caching