To work with easycaching, you have to configure where the cache is saved and how it is serialized, here is an example of using Newtonsoft.Json for serialization and disk folder for storage
Install the following packages:
EasyCaching.Core
EasyCaching.Disk
EasyCaching.InMemory
EasyCaching.Serialization.Json
Configure the caching service
builder.Services.AddEasyCaching(option =>
{
option.WithJson((JsonSerializerSettings jsonSerializerSettings) =>
{
jsonSerializerSettings.Error = (s, a) => a.ErrorContext.Handled = true;
jsonSerializerSettings.ContractResolver = new DefaultContractResolver
{
IgnoreSerializableInterface = true
};
}, "json");
option.UseDisk(config =>
{
config.DBConfig = new DiskDbOptions { BasePath = builder.Configuration["CacheFolder"] };
config.CacheNulls = false;
config.SerializerName = "json";
});
});
Inject in your service:
IEasyCachingProvider _cacheProvider;
Store and retreive the values:
await _cacheProvider.SetAsync("key", "value", TimeSpan.FromDays(1));
CacheValue<string> cacheValue = await _cacheProvider.GetAsync<string>("key");
if (cacheValue.HasValue) {
Console.WriteLine(cacheValue.Value);
}
Read more from here:
https://easycaching.readthedocs.io/en/latest/