-
Notifications
You must be signed in to change notification settings - Fork 1
2. Getting started
Vladyslav Lobyntsev edited this page Mar 5, 2024
·
2 revisions
Here is a simple example of using a memory cache in an ASP.NET Core application. Check samples for more.
Define the caching configuration in the ASP.NET Core startup file
builder.Services.AddFluentCaching(cacheBuilder => cacheBuilder
.For<Cart>(_ => _.UseAsKey(c => $"card-{c.Id}").And().SetExpirationTimeoutTo(5).Minutes
.With().SlidingExpiration().And().StoreInMemory())
Inject ICache object and use it
app.MapPost("/cart-items", async ([FromBody] CartItemDto dto, ICache cache) =>
{
var cart = await cache.RetrieveAsync<Cart>(dto.CartId) ?? new Cart(dto.CartId);
var existingItem = cart.Items.FirstOrDefault(i =>
i.ProductName.Equals(dto.ProductName, StringComparison.InvariantCultureIgnoreCase));
if (existingItem != null)
{
existingItem.Quantity += dto.Quantity;
}
else
{
cart.Items.Add(new CartItem(dto.ProductName, dto.Quantity));
}
await cache.CacheAsync(cart);
});
app.MapGet("/{cartId:guid}/cart-items", (Guid cartId, ICache cache) => cache.RetrieveAsync<Cart>(cartId));