In Java Spring Boot, I can easily enable caching using the annotation @EnableCaching
and make methods cache the result using @Cacheable
, this way, any input to my method with the exact same parameters will NOT call the method, but return immediately using the cached result.
Is there something similar in C#?
What I did in the past was i had to implement my own caching class, my own data structures, its a big hassle. I just want an easy way for the program to cache the result and return the exact result if the input parameters are the same.
EDIT: I dont want to use any third party stuff, so no MemCached, no Redis, no RabbitMQ, etc… Just looking for a very simple and elegant solution like Java’s @Cacheable
.
2
Answers
Caches
A cache is the most valuable feature that Microsoft provides. It is a type of memory that is relatively small but can be accessed very quickly. It essentially stores information that is likely to be used again. For example, web browsers typically use a cache to make web pages load faster by storing a copy of the webpage files locally, such as on your local computer.
Caching
Caching is the process of storing data into cache. Caching with the C# language is very easy. System.Runtime.Caching.dll provides the feature for working with caching in C#. In this illustration I am using the following classes:
ObjectCache
MomoryCache
CacheItemPolicy
: The CacheItem class provides a logical representation of a cache entry, that can include regions using the RegionName property. It exists in the System.Runtime.Caching.
: This class also comes under System.Runtime.Caching and it represents the type that implements an in-cache memory.
: Represents a set of eviction and expiration details for a specific cache entry.
.NET
providesSystem.Web.Caching.Cache
– default caching mechanizm inASP.NET
. You can get instance of this class via propertyController.HttpContext.Cache
also you can get it via singletonHttpContext.Current.Cache
. This class is not expected to be created explicitly because under the hood it uses another caching engine that is assigned internally. To make your code work the simplest way is to do the following:System.Runtime.Caching.MemoryCache – this class can be constructed in user code. It has the different interface and more features like
updateremove
callbacks, regions, monitors etc. To use it you need to import librarySystem.Runtime.Caching
. It can be also used inASP.net
application, but you will have to manage its lifetime by yourself.You can write a decorator with a get-or-create functionality. First, try to get value from cache, if it doesn’t exist, calculate it and store in cache:
ICacheClient
is the interface you’re extending. Now you can use: