using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DotNetMashup.Web.Global; using DotNetMashup.Web.Model; using DotNetMashup.Web.Repositories; using Microsoft.Framework.Caching.Memory; namespace DotNetMashup.Web.Factory { public class RepositoryFactory { private readonly IMemoryCache cache; private List Repos; private const string cacheKey = "data"; public RepositoryFactory(IEnumerable data, ISiteSetting setting, IMemoryCache cache) { if(data == null) { throw new ArgumentNullException("data"); } if(setting == null) { throw new ArgumentNullException("setting"); } if(cache == null) { throw new ArgumentNullException("cache"); } Repos = new List() { new GitHubRepository(), new BlogPostRepository(data, setting) }; this.cache = cache; } public async Task> GetData() { var cachedData = this.cache.Get>(cacheKey); if(cachedData != null && cachedData.Count > 0) return cachedData; var tasks = Repos.Select(a => a.GetData()); await Task.WhenAll(tasks); var result = tasks.SelectMany(a => a.Result).OrderBy(a => a.PublishedDate).ToList(); cache.Set(cacheKey, result, new MemoryCacheEntryOptions { AbsoluteExpiration = DateTime.Now.AddHours(4) }); return result; } } }