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")
...
}
}
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")
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With