我具有用于缓存的服务类 PersonsCachingService ,并且在更改此表中的记录数时,我需要重置“所有人”键。 在像Yii2或Symfony这样的PHP框架中,这样的任务很容易,但是我不了解在Asp Core中执行此操作的更好方法。 你能提出任何建议吗?
public class PersonsCachingService
{
private readonly ApplicationDbContext _dbContext;
private readonly IMemoryCache _memoryCache;
private static readonly int timeInSeconds = 30;
public PersonsCachingService(ApplicationDbContext dbContext, IMemoryCache memoryCache)
{
_dbContext = dbContext;
_memoryCache = memoryCache;
}
/// <summary>
/// Get all table from cache
/// </summary>
public IList<Person> AllPersons
{
get
{
string cacheKey = "allpersons";
if (_memoryCache.TryGetValue(cacheKey, out IList<Person> persons)) return persons;
else
{
persons = _dbContext.Persons.ToList();
_memoryCache.Set(cacheKey, persons, new MemoryCacheEntryOptions()
.SetAbsoluteExpiration(TimeSpan.FromSeconds(timeInSeconds)));
return persons;
}
}
}}