asp.net-coreasp.net-core-viewcomponentin-memory-cache

ASP.NET Core 6 - using memorycache in view component


I am writing an application using ASP.NET Core 6 MVC.

I have a controller that instantiates an IMemoryCache and stores some values into the cache.

public HomeController(ILogger<HomeController> logger, IMemoryCache memoryCache)
{
    _logger = logger;
    _cache = memoryCache;
}

In some other part of the application I assign a value to the cache.

In the _Layout.cshtml I am using a view component

 @await Component.InvokeAsync("Menu")

I need to access the cache from the view component.

I set IMemoryCache in the constructor, and the try to get the data.

public class MenuViewComponent : ViewComponent
{
    private const string ClientInfoCacheKey = "ClientInfo";
    private  IMemoryCache _cache;

    public async Task<IViewComponentResult> InvokeAsync(IMemoryCache memoryCache)
    {
         _cache = memoryCache;
         var fromCache = _cache.Get<string>(ClientInfoCacheKey);
         // ......
    }
}

But the problem I am facing is that _cache is always null...

Is there a way to access cache from a view component?

Thanks


Solution

  • You should inject IMemoryCache to your MenuViewComponent from constructor. Your code should be:

    public class MenuViewComponent : ViewComponent
    {
        private const string ClientInfoCacheKey = "ClientInfo";
        private readonly IMemoryCache _cache;
    
        public MenuViewComponent(IMemoryCache memoryCache)
        {
            _cache = memoryCache;
        }
    
        public async Task<IViewComponentResult> InvokeAsync()
        {         
             var fromCache = _cache.Get<string>(ClientInfoCacheKey);
             // ......
        }
    }