I am a beginner in the ASP.NET Core. Now, I am building diploma project "EducationManagementSystem for teachers". Of course, I understand, that it's a difficult project for beginners, but in the process of development I ran into a problem. So, the problem is: I have a 3 projects in the same solution:
- ASP.NET Core Web API;
- ASP.NET Core MVC;
- DataAccess (c# library for database entities etc).
So, in the web API application I'm interacting with the DataAccess and manipulating some data. Client, using the MVC project and accordingly UI, interacts with the WEB API and get some data, delete, put etc. And, I use IMemoryCache interface for caching results of MVC controller on the server side and check if there is a cache, then User get it from the cache, otherwise get it from the database (code below).
[ActionName("students")] [HttpGet] public async Task Students() { userId ??= HttpContext.User.FindFirstValue(ClaimTypes.Name)!; cacheKey_students = $"studentsOf_{userId}"; var studentsData = await _cacheService.GetOrSetAsync(cacheKey_students, async () => { var coursesList = await GetCourses(userId); var squadsList = await GetSquads(userId); var studentsVM = new StudentsPageViewModel { coursesList = coursesList, squadsList = squadsList }; return studentsVM; }, TimeSpan.FromDays(7)); return PartialView(studentsData); } But if some data has changed before expire time of cache, the cache won't be refresh, and to solve this problem I use custom CacheService (int the DataAccess project) for getting, setting and invalidating cache (code below):
public class CacheService : ICacheService { private readonly IMemoryCache _memoryCache; public CacheService(IMemoryCache memoryCache) { _memoryCache = memoryCache; } public async Task GetOrSetAsync(string key, Func getItemFunc, TimeSpan expirationTime) { if (!_memoryCache.TryGetValue(key, out T item)) { item = await getItemFunc(); if (item != null) { var cacheEntryOptions = new MemoryCacheEntryOptions() .SetAbsoluteExpiration(expirationTime); _memoryCache.Set(key, item, cacheEntryOptions); } } return item; } public bool InvalidateCache(string key) { try { _memoryCache.Remove(key); return true; } catch { return false; } } } But when I use this service in the MVC project and Web API project at the same time (with services.AddSingleton) it does not work, when I invalidate cache from Web API project (when some data has changed). So, I figured out that they are using different cache memory, so my question is: how to deal with it? Using something like Redis or there is another way? I think maybe we can create some listener in the MVC project, that will listening Web API project and when some WEB API controller says "Rerfresh the cache" MVC project will do it. Thanks in advance for the answers!
Источник: https://stackoverflow.com/questions/780 ... -same-time
Мобильная версия