So I have a need to use IMemoryCache in my ASP.NET Core application, in most places it is DI'd into the controllers and works as expected. Now I have a need to cache part of the menu, and the menu logic is called as part of the layout view. So, there isn't a controller to speak of. My Startup has the following in it already, which works well for other things:
services.AddMemoryCache();
The call that is part of the layout looks like this:
@(await new MenuUtility().DisplayNavBar(Html, showMenus))
The MenuUtility class, which is where the cache will be used, has a call that looks like this:
public class MenuUtility
{
private IMemoryCache _cache;
public MenuUtility()
{
_cache = HttpContext.Current.RequestServices.GetService<MemoryCache>();
}
// Rest of class logic
}
The problem is, the cache service I am looking to return is always null. Is there something I am forgetting? I tried to add services.AddScoped<MenuUtility>(); to the ConfigureServices call, thinking that this would allow me to pass the cache interface in the constructor, but since I am calling the MenuUtility explicitly I don't have the parameter of the cache to pass in.
I see a few questions here in SO that talk around this issue, but nothing that directly and correctly answers it.
Since this is my project for which I will forever be the only programmer, I would prefer a simple solution instead of suggestions to rearchitect a bunch of it, if I can't come up with a good solution I will just leave out the cache for this.