简体   繁体   中英

Memory cache seems to differ between endpoints in Asp.Net Core Web Api

I am having a problem with using a memory cache (tried both IMemoryCache and IDistributedCache with respectively AddMemoryCache() and AddDistributedMemoryCache ). It seems that the cache is not shared between endpoints of my asp.net core 2.2 web api, but it is shared for requests of 1 endpoint. The cache is injected in constructor of singleton service.

And here is what is my concern:
1) Request go to endpoint A, it calls API, store response to cache and return it.
2) Next request go for endpoint A and... successfuly get response for cache - OK.
3) But when calling an entpoint B then I cannot get response for cache (using same key) and the cache seems to be empty

EDIT: After checking I found out that I really get another instances of MemoryCache for different endpoints of my API.

EDIT2: Code samples DI:

            services.AddDistributedMemoryCache();
            services.AddSingleton<ICacheStore, CacheStore>();
            services.AddScoped<CosmosDbUserRepository>();
            services.AddScoped<IUserRepository>(sp =>
            {
                var realRepository = sp.GetRequiredService<CosmosDbUserRepository>();
                var cache = sp.GetRequiredService<ICacheStore>();
                return new CachedUserRepository(realRepository, cache);
            });

CacheStore:

  internal class CacheStore : ICacheStore
    {
        private static readonly JsonSerializer Serializer = new JsonSerializer();
        private readonly IDistributedCache _cache;

        public CacheStore(IDistributedCache cache)
        {
            _cache = cache ?? throw new ArgumentNullException(nameof(cache));
        }
    }

Sample endpoints:

        [HttpGet]
        [ProducesResponseType(typeof(UserDetails), (int)HttpStatusCode.OK)]
        public async Task<IActionResult> GetUserDetails(
            [FromServices] QueryMediator mediator)
        {
            return Ok(
                await mediator.HandleQuery<GetUserDetailsQuery, UserDetails>(null));
        }

        [HttpPatch("username")]
        [ProducesResponseType((int)HttpStatusCode.NoContent)]
        public async Task<IActionResult> ChangeUsername(
            [FromBody] ChangeUsernameCommand command,
            [FromServices] CommandMediator mediator)
        {
            await mediator.HandleCommand(command);
            return NoContent();
        }

Problem solved: After hours I've tried to create an instance of cache in startup and register the specific instance as Singleton. It worked: But for now I'm trying to reproduce the issue with smaller application and create an issue for this:) Code below:

            var memoryCache = new MemoryDistributedCache(
                Options.Create(new MemoryDistributedCacheOptions()));
            services.AddSingleton<IDistributedCache>(memoryCache);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM