0

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

0

1 Answer 1

1

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);
         // ......
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.