The simplest can be used the Cache in-memory in ASP.NET Core (translation: Memory cache) that can be configured in seconds, minutes, days, etc. its permanence in the information memory, that is, according to your need.
To enable this code in your project on startup.cs
in the method ConfigureServices
call the extension method .AddMemoryCache()
as shown in the code:
public void ConfigureServices(IServiceCollection services)
{
services.AddMemoryCache(); // adicione essa linha para funciona cache em memoria
services.AddRazorPages();
}
is now enabled to be used in Pages Razor
and how you are in a battle in a few questions (1 and 2) follows the same example below:
Add a property:
public IMemoryCache MemoryCache { get; private set; }
then in the construtor
of his PageModel
pass to interface
and assign the property previously created for the injection that is passed in the construtor
:
public MostrarModel(IMemoryCache memoryCache)
{
MemoryCache = memoryCache;
}
from this has the possibility to create cache of the information in the memory of any type and by a simple decision structure can seek the value in the cache or create the value and store in cache for an amount of time (in the case example just below the full code was added thirty minutes, but as has already been reported by being configured days and hours its way):
Final code:
public class MostrarModel : PageModel
{
public Country[] Countries { get; private set; }
public IMemoryCache MemoryCache { get; private set; } // cache
public MostrarModel(IMemoryCache memoryCache) // injeção
{
MemoryCache = memoryCache; // atribuição
}
public async Task OnGetAsync()
{
//chave do cache (cada valor armazenado tem a sua)
string key = "countries_cache";
//verificando se o valor está ou não em cache e tomando as medidas
//dependendo da decisão na estrutura
if (!MemoryCache.TryGetValue<Country[]>(key, out Country[] values))
{
var create = RestService
.For<IGetRootobject>("https://api.covid19api.com/summary");
var result = await create.GetAsync();
Countries = result.Countries;
//Armazenando em cache
MemoryCache.Set(key, Countries, System.TimeSpan.FromMinutes(30));
}
else
{
//recuperando do cache
Countries = values;
}
}
}
The other way is with Distributed caching in ASP.NET Core that in this case is information shared on multiple servers that greatly improves performance and scalability and its configuration is similar to the previous:
Add the extension method:
services.AddDistributedMemoryCache();
and in the constructor and in the code are very similar to the previous
private readonly Idistributedcache Memorycache;
public MostrarModel(IDistributedCache memoryCache)
{
MemoryCache = memoryCache;
}
and with the methods GetAsync
to recover and SetAsync
to record the cache.
Several types still exist as:
Which would be the most recommended? Cache in-memory in ASP.NET Core or Distributed caching in ASP.NET Core ?
– Eduardo Nogueira
You can use in-memory cache @eduardonogueira
– novic