我创建了一个新的ASP.NET Core Web API项目。这是Startup.cs中的ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddMemoryCache();
var serviceProvider = services.BuildServiceProvider();
var cache = serviceProvider.GetService<IMemoryCache>();
cache.Set("key1", "value1");
//_cahce.Count is 1
}
如您所见,我向IMemoryCache添加了一个项目。这是我的控制器:
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IMemoryCache _cache;
public ValuesController(IMemoryCache cache)
{
_cache = cache;
}
[HttpGet("{key}")]
public ActionResult<string> Get(string key)
{
//_cahce.Count is 0
if(!_cache.TryGetValue(key, out var value))
{
return NotFound($"The value with the {key} is not found");
}
return value + "";
}
}
当我请求https://localhost:5001/api/values/key1
时,缓存为空,并且收到未找到的响应。
答案 0 :(得分:3)
简而言之,您要在其中设置值的缓存实例与以后要检索的实例不同。您无法进行诸如构建虚拟主机的操作(例如,在ConfigureServices
/ Configure
中进行操作。如果您需要在启动时进行某些操作,则需要在构建虚拟主机后进行操作,例如{ {1}}:
Program.cs
答案 1 :(得分:2)
正如@selloape所说,如果您手动调用BuildServicesProvider,则说明您正在创建一个新的提供程序,它将不会在控制器中使用。
您可以使用托管服务来初始化缓存
public class InitializeCacheService : IHostedService
{
private readonly IServiceProvider _serviceProvider;
public InitializeCacheService (IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public Task StartAsync(CancellationToken cancellationToken)
{
using (var scope = _serviceProvider.CreateScope())
{
var cache = _serviceProvider.GetService<IMemoryCache>();
cache.Set("key1", "value1");
}
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}
将其添加到您的ConfigureServices
services.AddHostedService<InitializeCacheService>();
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-2.2