This app demonstrates how to use HybridCache in .NET 10 to improve performance with hybrid caching strategies that combine in-memory and distributed cache layers. It provides a simple API example showing caching best practices.
dotnet run api.csThis app demonstrates how to use HybridCache in .NET 10 to improve performance with hybrid caching strategies that combine in-memory and distributed cache layers. It provides a simple API example showing caching best practices.
dotnet run api.cs| #:sdk Microsoft.NET.Sdk.Web | |
| #:package Microsoft.Extensions.Caching.Hybrid@10.* | |
| #:property PublishAot=false | |
| using Microsoft.Extensions.Caching.Hybrid; | |
| WebApplicationBuilder builder = WebApplication.CreateBuilder(args); | |
| builder.Services.AddHybridCache(); | |
| builder.Services.AddSingleton<IWeatherService, WeatherService>(); | |
| WebApplication app = builder.Build(); | |
| app.UseHttpsRedirection(); | |
| app.MapGet("/", () => "Hello World!"); | |
| app.MapGet("/forecast", async (IWeatherService weather, CancellationToken cancellationToken) => | |
| { | |
| return await weather.GetForecastsAsync(cancellationToken); | |
| }); | |
| await app.RunAsync(); | |
| record WeatherForecast( | |
| DateOnly Date, | |
| int TemperatureC, | |
| string? Summary | |
| ) | |
| { | |
| public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); | |
| } | |
| interface IWeatherService | |
| { | |
| Task<WeatherForecast[]> GetForecastsAsync(CancellationToken cancellationToken = default); | |
| } | |
| class WeatherService(HybridCache cache) : IWeatherService | |
| { | |
| private static readonly string[] Summaries = | |
| [ | |
| "Freezing", "Bracing", "Chilly", "Cool", "Mild", | |
| "Warm", "Balmy", "Hot", "Sweltering", "Scorching" | |
| ]; | |
| public async Task<WeatherForecast[]> GetForecastsAsync(CancellationToken cancellationToken = default) | |
| { | |
| return await cache.GetOrCreateAsync( | |
| "weather:forecast", | |
| GenerateForecastsAsync, | |
| cancellationToken: cancellationToken); | |
| } | |
| private static async ValueTask<WeatherForecast[]> GenerateForecastsAsync(CancellationToken cancellationToken) | |
| { | |
| await Task.Delay(TimeSpan.FromSeconds(3), cancellationToken); | |
| // Simulate an expensive operation to generate forecasts. | |
| return [.. Enumerable.Range(1, 5).Select(index => | |
| new WeatherForecast( | |
| DateOnly.FromDateTime(DateTime.Now.AddDays(index)), | |
| Random.Shared.Next(-20, 55), | |
| Summaries[Random.Shared.Next(Summaries.Length)] | |
| ))]; | |
| } | |
| } |
| @host = http://localhost:5000 | |
| ### Greet with "Hello, World!" | |
| GET {{host}}/ | |
| Accept: text/plain | |
| ### Get weather forecast | |
| GET {{host}}/forecast | |
| Accept: application/json |