.NET comes with a built in caching service called IMemoryCache that caches data in memory for faster access by reducing the load on database or external services. This is under the namespace of Microsoft.Extensions.Caching.Memory and being an in memory cache implementation, allows storing and retrieving data. Here’s how you can use IMemoryCache in a .NET application:
Step 1: Install the required package
dotnet add package Microsoft.Extensions.Caching.Memory public void ConfigureServices(IServiceCollection services)
Step 2: Configure IMemoryCache in Startup.cs
{
// Add memory caching
services.AddMemoryCache();
// Add other services here
}
1. Set Data to IMemoryCache
using System;
using Microsoft.Extensions.Caching.Memory;
public class MyService
{
private readonly IMemoryCache _memoryCache;
public MyService(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
public object GetData(string key)
{
// Checking for data available in the memory cache
if (_memoryCache.TryGetValue(key, out object cachedData))
{
return cachedData; // Return cached data
}
// Data is not in cache, fetch it (e.g., from database or API)
cachedData = FetchDataFromDatabase(key);
// Store the fetched data in cache for subsequent requests
_memoryCache.Set(key, cachedData, TimeSpan.FromMinutes(5)); // Set cache expiration time
return cachedData;
}
private object FetchDataFromDatabase(string key)
{
// Simulate database call
return new { Key = key, Value = "Fetched Data" };
}
}
2. Expiration Options
_memoryCache.set(key, value, DateTimeOffset.Now.AddMinutes(10));
_memoryCache.Set(
key,
value,
new MemoryCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(10)
});
3. Removing data from the cache
_memoryCache.Remove(key);
_memoryCache.Clear();
IMemoryCache appropriate utilization can increase the performance of your application by avoiding the repeated operation or request to the database.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our .Net Expertise.
0