Blazor server side add memory cache

Posted 3 years ago by xicoJosue
0

Hello,

Anyone knows how to add/implement "in memory caching" on blazor server side, like in MVC?

I cannot find any article about this.

I need to save data in Memory cache on the server and load it in a razor component or a ViewModel.

I need this as soon as possible for a project.

startup.cs --> services.AddMemoryCache();

Reference Example:

https://www.codewithmukesh.com/blog/in-memory-caching-in-aspnet-core/

Thank You

  • 1

    This should generally work similar to the way it does in MVC. You could perform the caching in a service and call it from Blazor. Here's a basic example, but keep in mind you'd need to adjust your sliding and absolute expiration to meet your needs and you might need to serialize the object you're caching. This example is just using a string.

    In a default Blazor server project, open up the Startup.cs file and add services.AddMemoryCache(); to the ConfigureServices method.

    Now open up the WeatherForecastService.cs file (it's in the Data folder) and add the following into the top of the class

    private readonly IMemoryCache _memoryCache;
    public WeatherForecastService(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }
    
    public string GetSetSampleCache(string ticks)
    {
        string key = "_Key_SampleCache";
        var encodedCache = _memoryCache.Get(key);
                
        if(encodedCache == null)
        {     
            var options = new MemoryCacheEntryOptions()
                .SetSlidingExpiration(TimeSpan.FromSeconds(5))
                .SetAbsoluteExpiration(DateTime.Now.AddMinutes(1));
            _memoryCache.Set(key, ticks, options);
            return _memoryCache.Get(key).ToString();
        }
        else
        {
            return _memoryCache.Get(key).ToString();
        }
    }

    You'll also need to add a using directive to the top of the file

    using Microsoft.Extensions.Caching.Memory;

    Next, open up the FetchData.razor component and adjust it to include the following code

    @page "/fetchdata"
    @using YourProjectNameHere.Data
    @inject WeatherForecastService ForecastService
    
    <h1>Weather forecast</h1>
    
    <p>This component demonstrates fetching data from a service.</p>
    
    @* // This is the cached data *@
    <h2>Ticks</h2>
    <p>@ticks</p>
    
    @if (forecasts == null)
    {
        <p><em>Loading...</em></p>
    }
    else
    {
        <table class="table">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Temp. (C)</th>
                    <th>Temp. (F)</th>
                    <th>Summary</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var forecast in forecasts)
                {
                    <tr>
                        <td>@forecast.Date.ToShortDateString()</td>
                        <td>@forecast.TemperatureC</td>
                        <td>@forecast.TemperatureF</td>
                        <td>@forecast.Summary</td>
                    </tr>
                }
            </tbody>
        </table>
    }
    
    @code {
        private WeatherForecast[] forecasts;
        string ticks;
    
        protected override async Task OnInitializedAsync()
        {
            forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
            ticks = ForecastService.GetSetSampleCache(DateTime.Now.Ticks.ToString());
        }
    }

    Now when you run the app and go to the "Fetch data" page, you'll see that if you refresh the page in cycles less than 5 seconds, it keeps showing the same tick data. If you wait 5 seconds and refresh again, the tick data will be refreshed.

    Posted 3 years ago by selliott Edited 3 years ago
Someone is typing...

Post a Reply

You must be logged in to add a new post.
Number of online users: 1
An error has occurred. This application may no longer respond until reloaded. Reload 🗙