|
| 1 | +using Microsoft.Extensions.Caching.Memory; |
| 2 | + |
1 | 3 | namespace BlazorSample;
|
2 | 4 |
|
3 |
| -public class WeatherForecastService |
| 5 | +public class WeatherForecastService(IMemoryCache memoryCache) |
4 | 6 | {
|
5 |
| - private static readonly string[] Summaries = |
| 7 | + private static readonly string[] summaries = |
6 | 8 | [
|
7 |
| - "Freezing", |
8 |
| - "Bracing", |
9 |
| - "Chilly", |
10 |
| - "Cool", |
11 |
| - "Mild", |
12 |
| - "Warm", |
13 |
| - "Balmy", |
14 |
| - "Hot", |
15 |
| - "Sweltering", |
16 |
| - "Scorching" |
| 9 | + "Freezing", "Bracing", "Chilly", "Cool", "Mild", |
| 10 | + "Warm", "Balmy", "Hot", "Sweltering", "Scorching" |
17 | 11 | ];
|
18 | 12 |
|
19 |
| - public Task<WeatherForecast[]> GetForecastAsync(DateOnly startDate) |
| 13 | + public IMemoryCache MemoryCache { get; } = memoryCache; |
| 14 | + |
| 15 | + public Task<WeatherForecast[]?> GetForecastAsync(DateOnly startDate) |
20 | 16 | {
|
21 |
| - return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast |
| 17 | + return MemoryCache.GetOrCreateAsync(startDate, async e => |
22 | 18 | {
|
23 |
| - Date = startDate.AddDays(index), |
24 |
| - TemperatureC = Random.Shared.Next(-20, 55), |
25 |
| - Summary = Summaries[Random.Shared.Next(Summaries.Length)] |
26 |
| - }).ToArray()); |
| 19 | + e.SetOptions(new MemoryCacheEntryOptions |
| 20 | + { |
| 21 | + AbsoluteExpirationRelativeToNow = |
| 22 | + TimeSpan.FromSeconds(30) |
| 23 | + }); |
| 24 | + |
| 25 | + var rng = new Random(); |
| 26 | + |
| 27 | + await Task.Delay(TimeSpan.FromSeconds(10)); |
| 28 | + |
| 29 | + return Enumerable.Range(1, 5).Select(index => new WeatherForecast |
| 30 | + { |
| 31 | + Date = startDate.AddDays(index), |
| 32 | + TemperatureC = rng.Next(-20, 55), |
| 33 | + Summary = summaries[rng.Next(summaries.Length)] |
| 34 | + }).ToArray(); |
| 35 | + }); |
27 | 36 | }
|
28 | 37 | }
|
0 commit comments