更改数据库表时的IMemoryCache删除键

时间:2018-06-25 13:06:49

标签: asp.net-core

我具有用于缓存的服务类 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;
            }

        }
    }}

0 个答案:

没有答案
相关问题