Skip to content

Commit

Permalink
Cached Repository
Browse files Browse the repository at this point in the history
  • Loading branch information
goodtocode committed Jul 10, 2023
1 parent 8f5cb36 commit 65d7bc9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,53 +3,60 @@

namespace Goodtocode.Common.Persistence.Repository;

public class GenericRepository<T> : IGenericRepository<T> where T : class
public class CacheRepository<T> : ICacheRepository<T> where T : class
{
private readonly static CacheTypes CacheTypes = CacheTypes.Memory;
private readonly static CacheTypes CacheType = CacheTypes.Memory;
private readonly string cacheKey = $"{typeof(T)}";
private readonly DbContext _dbContext;
private readonly Func<CacheTypes, ICacheService> _cacheService;
public GenericRepository(DbContext dbContext, Func<CacheTypes, ICacheService> cacheService)

public CacheRepository(DbContext dbContext, Func<CacheTypes, ICacheService> cacheService)
{
_dbContext = dbContext;
_cacheService = cacheService;
}

public virtual async Task<T> GetByIdAsync(int id)
{
return await _dbContext.Set<T>().FindAsync(id);
}

public async Task<IReadOnlyList<T>> GetAllAsync()
{
if (!_cacheService(CacheTypes).TryGet(cacheKey, out IReadOnlyList<T> cachedList))
if (!_cacheService(CacheType).TryGet(cacheKey, out IReadOnlyList<T> cachedList))
{
cachedList = await _dbContext.Set<T>().ToListAsync();
_cacheService(CacheTypes).Set(cacheKey, cachedList);
_cacheService(CacheType).Set(cacheKey, cachedList);
}
return cachedList;
}

public async Task<T> AddAsync(T entity)
{
await _dbContext.Set<T>().AddAsync(entity);
await _dbContext.SaveChangesAsync();
await RefreshCache();
return entity;
}

public async Task UpdateAsync(T entity)
{
_dbContext.Entry(entity).State = EntityState.Modified;
await _dbContext.SaveChangesAsync();
await RefreshCache();
}

public async Task DeleteAsync(T entity)
{
_dbContext.Set<T>().Remove(entity);
await _dbContext.SaveChangesAsync();
await RefreshCache();
}

public async Task RefreshCache()
{
_cacheService(CacheTypes).Remove(cacheKey);
_cacheService(CacheType).Remove(cacheKey);
var cachedList = await _dbContext.Set<T>().ToListAsync();
_cacheService(CacheTypes).Set(cacheKey, cachedList);
_cacheService(CacheType).Set(cacheKey, cachedList);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace Goodtocode.Common.Persistence.Repository;

public interface IGenericRepository<T> where T : class
public interface ICacheRepository<T> where T : class
{
Task<T> GetByIdAsync(int id);
Task<IReadOnlyList<T>> GetAllAsync();
Expand Down

0 comments on commit 65d7bc9

Please sign in to comment.