.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.
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
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);
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.
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 - ssukhpinder/DotnetAspireChallenge: 10 Day .Net Aspire Challenge
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