A Guide to Cached Repository Pattern in .NET
What is the Cached Repository Pattern in .NET?
The Cached Repository Pattern combines the traditional repository pattern with caching to optimize performance. When retrieving data, the repository first checks the cache. If the data is found there, it is retrieved from the cache. Otherwise, it accesses the data source (such as a database) and caches the retrieved data. This approach helps reduce the load on the data source and improves response times.
Why Use the Cached Repository Pattern?
The Cached Repository Pattern offers several benefits:
1. Improved Performance: By caching frequently accessed data, you can significantly reduce the time it takes to retrieve information.
2. Reduced Database Load: Caching reduces the number of database queries, which can help prevent performance bottlenecks.
3. Consistent Data: Cached data remains consistent across requests, even if the underlying data changes.
4. Background Caching: You can set up background jobs (using tools like Hangfire) to refresh the cache periodically, ensuring that the data remains up-to-date.
Implementation Example
Let’s walk through an example of implementing the Cached Repository Pattern in an ASP.NET Core application.
Step 1: Define the Student Entity
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Step 2: Create the Repository Interface
public interface IRepository<TEntity>
{
List<TEntity> List();
}
Step 3: Implement the Student Repository
public class StudentRepository : IRepository<Student>
{
private readonly AppDbContext _context;
public StudentRepository(AppDbContext dbContext) => _context = dbContext;
public List<Student> List() => _context.Student.ToList();
}
Step 4: Implement the Cached Repository
public class CachedStudentRepository : IRepository<Student>
{
private readonly StudentRepository _studentRepository;
private readonly IMemoryCache _memoryCache;
private const string CacheKey = "Students";
public CachedStudentRepository(StudentRepository studentRepository, IMemoryCache memoryCache)
{
_studentRepository = studentRepository;
_memoryCache = memoryCache;
}
public List<Student> List()
{
return _memoryCache.GetOrCreate(CacheKey, entry =>
{
entry.SetOptions(new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(20)));
return _studentRepository.List();
})!;
}
}
Step 5: Register Services in Program.cs
builder.Services.AddScoped<IRepository<Student>, CachedStudentRepository>();
builder.Services.AddScoped<StudentRepository>();
builder.Services.AddSingleton<IMemoryCache, MemoryCache>();
Now you have a Cached Repository that retrieves student data from the cache or the database, depending on availability. Remember to adjust the cache key and expiration time according to your requirements.
For more updates and insights, and to connect with me, feel free to follow me on LinkedIn:
Let’s stay connected and continue the conversation! 🚀