Step-by-step guide on how to use the .Net Aspire Redis Cache component in Visual Studio.
Introduction
.Net Aspire framework is used to develop cloud and production-ready distributed applications. It consists of components to handle cloud-native concerns such as Redis, Postgres etc.
Prerequisites
Install .Net 8
Install Visual Studio 2022 version 17 or higher
.Net Aspire Workload
Container runtime such as Docker Desktop
10 Day .Net Aspire Challenge
Objectives
Learn how to create a starter project using .Net Aspire with the Redis Cache.
Github Sample: The solution structure is divided into the following projects
DotnetAspireChallenge.ApiService
DotnetAspireChallenge.AppHost
DotnetAspireChallenge.ServiceDefaults
DotnetAspireChallenge.Web
Getting Started
Step 1: Install the following NuGet package
Install the following Nuget package into the subsequent project “DotnetAspireChallenge.AppHost”
dotnet add package Aspire.Hosting.Oracle
In the above project, register a server database and consume the Oracle connection using the following code.
var cache = builder.AddRedis("cache");
builder.AddProject<Projects.DotnetAspireChallenge_Web>("webfrontend")
.WithExternalHttpEndpoints()
.WithReference(cache);
Step 2: Install another NuGet package
Install the following Nuget package into the subsequent project “DotnetAspireChallenge.ApiService”
dotnet add package Aspire.StackExchange.Redis.DistributedCache
then register the context into the Program.cs file as follows
builder.AddRedisDistributedCache("cache");
To add additional connection string properties using the JSON syntax
{
"Aspire": {
"StackExchange": {
"Redis": {
"ConfigurationOptions": {
"ConnectTimeout": 5000,
"ConnectRetry": 3
}
}
}
}
}
Congratulations..!! You’ve successfully integrated the Redis Cache component into the .Net Aspire project.
Output Cache
The HTML or any static content can be cached as well in a web app or a Blazer app.
// Add the output cache
builder.AddRedisOutputCache();
// Build the app
var app = builder.Build();
// Add the middleware
app.UseOutputCache();
To cache a razor page use the “OutputCache” attribute as follows
@page "/"
@attribute [OutputCache(Duration = 10)]
If your project requires to cache the response of APIs, you can use the same “OutputCache” attribute as follows
app.MapGet("/products/{ProdId}", (int ProdId) => $"The product ID is {ProdId}.").CacheOutput();
app.MapGet("/products/{ProdId}", [OutputCache] (int ProdId) => $"The product ID is {ProdId}.");
Github Project
GitHub - ssukhpinder/DotnetAspireChallenge: 10 Day .Net Aspire Challenge
More Cheatsheets
C# Programming🚀
Thank you for being a part of the C# community! Before you leave:
Follow us: Youtube | X | LinkedIn | Dev.to
Visit our other platforms: GitHub
More content at C# Programming
Top comments (0)