Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to resolve service for type 'Microsoft.Extensions.Caching.Memory.IMemoryCache'

I have a WEB API using .NET 6. I used MemoryCache to store data. But when I run the Api I get the following error:

Unable to resolve service for type 'Microsoft.Extensions.Caching.Memory.IMemoryCache'

myContoroler:

public class myContoroler : Controller
{
    private readonly MemoryCache _memoryCache = new MemoryCache(optionsAccessor: null);

    
   [HttpPost]
    public async Task<IActionResult> myAPI(Model modelS)
    {
      var users = _memoryCache.Get("UserData")
      ...
    }

 }

1 Answers

in your Startup.cs file, you need to introduce MemoryCache:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();
        .
        .
        .
    }

If there is no Startup.cs file, this should be done in Program.cs (in .NET 6.0, Startup.cs class is removed and Program.cs class is the place where register the dependencies of the application and the middleware.)

 builder.Services.AddMemoryCache();

It is also recommended to use dependency injection to use the MemoryCache in the controller:

public class myContoroler : Controller
{
    private readonly IMemoryCache _memoryCache;

    public myContoroler(IMemoryCache memoryCache)
    {
         _memoryCache = memoryCache;
    }

    [HttpPost]
    public async Task<IActionResult> myAPI(Model modelS)
    {
        var users = _memoryCache.Get("UserData")
        ...
    }

}
like image 143
Hossein Sabziani Avatar answered Sep 13 '25 05:09

Hossein Sabziani