A Simple Example of Using the Memory Cache in .NET 6 with API Endpoints
It took me a little longer than I expected to write the code for this example, and whenever that happens I assume it will take some other people more time than they expect too. That is why I am writing it down.
In principle it is very simple, I want to use a MemoryCache
inside an API endpoint. When the endpoint is called, the memory cache is injected into it.
I check the cache for the key I’m looking for. If the key is in the cache, I return the value. If the key is not in the cache, I do a fake lookup in the database, and then I add the key and value to the cache.
Once the code is complete it is very clear and easy to read, so I won’t add anything else. Hope this helps you.
1using Microsoft.Extensions.Caching.Memory;
2
3var builder = WebApplication.CreateBuilder(args);
4
5// Add services to the container.
6builder.Services.AddMemoryCache(); // add the memory cache to the service collection
7builder.Services.AddSingleton<Random>(); // add the random number generator to the service collection
8var app = builder.Build();
9
10app.MapGet("/Inventory/{itemId}", (int itemId, IMemoryCache memoryCache, Random random) =>
11{
12 Console.WriteLine($"You requested item:{itemId}, looking in cache...");
13 if (memoryCache.TryGetValue<int>(itemId, out var quantity))
14 {
15 Console.WriteLine($"Found item:{itemId}, in the cache!");
16 return Results.Ok($"Found item:{itemId}, in the cache. We have {quantity} in stock.");
17 }
18 else
19 {
20 Console.WriteLine("Could not find id:{id} in the cache! Searching the database...");
21 // Not really going to look in the database
22 quantity = random.Next(100);
23 memoryCache.Set(itemId, quantity, TimeSpan.FromSeconds(10));
24 return Results.Ok($"Found item:{itemId} in the database. We have {quantity} in stock. Adding it to the cache now.");
25 }
26});
27
28app.Run();