Sobes.tech
Middle+

IMemoryCache — what is it and when to use it?

sobes.tech AI

Answer from AI

IMemoryCache is an interface in .NET that provides a mechanism for caching data in the application's memory. It allows temporarily storing objects for quick access without the need for recalculating or loading from slower sources (such as databases or external services).

When to use IMemoryCache:

  • For caching frequently requested but rarely changed data.
  • To reduce load on the database or external APIs.
  • When high-speed data access is important.
  • In scenarios where data can be lost upon application restart (i.e., cache should not be persistent).

Example usage:

public class ProductService
{
    private readonly IMemoryCache _cache;

    public ProductService(IMemoryCache cache)
    {
        _cache = cache;
    }

    public Product GetProduct(int id)
    {
        return _cache.GetOrCreate(id, entry =>
        {
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10);
            return LoadProductFromDatabase(id);
        });
    }

    private Product LoadProductFromDatabase(int id)
    {
        // Simulate loading from DB
        return new Product { Id = id, Name = "Sample" };
    }
}

Thus, IMemoryCache is suitable for fast, local caching within a single application instance.