I have an MVC-based site, which is using a Repository/Service pattern for data access. The Services are written to be using in a majority of applications (console, winform, and web). Currently, the controllers communicate directly to the services. This has limited the ability to apply proper caching.
I see my options as the following:
I can see the pros and cons of each. What is/should the best practice be for caching with Repository/Service
In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action. Output caching basically allows you to store the output of a particular controller in the memory.
ASP.NET supports three types of caching: Page Output Caching [Output caching] Page Fragment Caching [Output caching] Data Caching.
Caching is used to improve the performance in ASP.NET MVC. Caching is a technique which stores something in memory that is being used frequently to provide better performance. In ASP.NET MVC, OutputCache attribute is used for applying Caching.
A cache repository is a storage location where Veeam Backup & Replication keeps temporary cached metadata for the data backed up by the file share backup jobs. For more information about cache repository, see NAS Backup Support.
Steve Smith did two great blog posts which demonstrate how to use his CachedRepository pattern to achieve the result you're looking for.
Introducing the CachedRepository Pattern
Building a CachedRepository via Strategy Pattern
In these two posts he shows you how to set up this pattern and also explains why it is useful. By using this pattern you get caching without your existing code seeing any of the caching logic. Essentially you use the cached repository as if it were any other repository.
public class CachedAlbumRepository : IAlbumRepository { private readonly IAlbumRepository _albumRepository; public CachedAlbumRepository(IAlbumRepository albumRepository) { _albumRepository = albumRepository; } private static readonly object CacheLockObject = new object(); public IEnumerable<Album> GetTopSellingAlbums(int count) { Debug.Print("CachedAlbumRepository:GetTopSellingAlbums"); string cacheKey = "TopSellingAlbums-" + count; var result = HttpRuntime.Cache[cacheKey] as List<Album>; if (result == null) { lock (CacheLockObject) { result = HttpRuntime.Cache[cacheKey] as List<Album>; if (result == null) { result = _albumRepository.GetTopSellingAlbums(count).ToList(); HttpRuntime.Cache.Insert(cacheKey, result, null, DateTime.Now.AddSeconds(60), TimeSpan.Zero); } } } return result; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With