Reputation: 182
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:
EDIT: after checking I found out that I really get another instances of MemoryCache
for different endpoints of my API.
EDIT #2: 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();
}
Upvotes: 2
Views: 2264
Reputation: 182
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);
Upvotes: 2