Caching in C#/.Net

前端 未结 12 1279
离开以前
离开以前 2020-11-30 02:22

I wanted to ask you what is the best approach to implement a cache in C#? Is there a possibility by using given .NET classes or something like that? Perhaps something like a

12条回答
  •  盖世英雄少女心
    2020-11-30 03:12

    - Memory cache implementation for .Net core

    public class CachePocRepository : ICachedEmployeeRepository
        {
            private readonly IEmployeeRepository _employeeRepository;
            private readonly IMemoryCache _memoryCache;
    
            public CachePocRepository(
                IEmployeeRepository employeeRepository,
                IMemoryCache memoryCache)
            {
                _employeeRepository = employeeRepository;
                _memoryCache = memoryCache;
            }
    
            public async Task GetEmployeeDetailsId(string employeeId)
            {
                _memoryCache.TryGetValue(employeeId, out Employee employee);
    
                if (employee != null)
                {
                    return employee;
                }
    
                employee = await _employeeRepository.GetEmployeeDetailsId(employeeId);
                
                _memoryCache.Set(employeeId,
                    employee,
                    new MemoryCacheEntryOptions()
                    {
                        AbsoluteExpiration = DateTimeOffset.UtcNow.AddDays(7),
                    });
    
                return employee;
    
            }
    

提交回复
热议问题