Using IInMemoryCache

The simplest cache is based on the IInMemoryCache, which represents a cache stored in the memory of the web server. Apps which run on a server farm of multiple servers should ensure that sessions are sticky when using the in-memory cache. Sticky sessions ensure that subsequent requests from a client all go to the same server.

Note

Some HTTP servers allow sticky sessions. For example, nginx supports session persistence, but there is no guarantee that the same client will be always directed to the same server. Thus we recommend using IInMemoryCache if and only if you have a single app server otherwise you should use some kind distributed cache, for instance, ISharedCache or ITwoLayerCache. Nonetheless, the in-memory cache can store any object; the distributed cache is limited by a database format.

To work with IInMemoryCache you need to make next steps.

1. Install InfinniPlatform.Cache.Memory package:

dotnet add package InfinniPlatform.Cache.Memory -s https://www.myget.org/F/infinniplatform/

2. Call AddInMemoryCache() in ConfigureServices():

 using System;

 using InfinniPlatform.AspNetCore;

 using Microsoft.Extensions.DependencyInjection;

 public class Startup
 {
     public IServiceProvider ConfigureServices(IServiceCollection services)
     {
         services.AddInMemoryCache();

         // ...

         return services.BuildProvider();
     }

     // ...
 }

3. Request the IInMemoryCache instance in the constructor:

 class MyComponent
 {
     private readonly IInMemoryCache _cache;

     public MyComponent(IInMemoryCache cache)
     {
         _cache = cache;
     }

     // ...
 }