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")
...
}
}
CodePudding user response:
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 MemoryCache _memoryCache;
public myContoroler(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
[HttpPost]
public async Task<IActionResult> myAPI(Model modelS)
{
var users = _memoryCache.Get("UserData")
...
}
}