Caching Data Objects when using Repository/Service Pattern and MVC

前端 未结 4 1982
囚心锁ツ
囚心锁ツ 2020-12-12 19:03

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,

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 19:46

    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 GetTopSellingAlbums(int count)
        {
            Debug.Print("CachedAlbumRepository:GetTopSellingAlbums");
            string cacheKey = "TopSellingAlbums-" + count;
            var result = HttpRuntime.Cache[cacheKey] as List;
            if (result == null)
            {
                lock (CacheLockObject)
                {
                    result = HttpRuntime.Cache[cacheKey] as List;
                    if (result == null)
                    {
                        result = _albumRepository.GetTopSellingAlbums(count).ToList();
                        HttpRuntime.Cache.Insert(cacheKey, result, null, 
                            DateTime.Now.AddSeconds(60), TimeSpan.Zero);
                    }
                }
            }
            return result;
        }
    }
    

提交回复
热议问题