gpt4 book ai didi

c# - IDistributedCache 可用但数据不再在缓存中?

转载 作者:太空宇宙 更新时间:2023-11-03 22:30:23 25 4
gpt4 key购买 nike

我正在使用 services.AddDistributedMemoryCache()在我的 .Net Core 3 Web API 中 startup.cs类(class)。当我第一次设置缓存时:

public void SetCommandEventMappingCache(IServiceCollection serviceCollection)
{
var cache = serviceCollection.BuildServiceProvider().GetService<IDistributedCache>();

var mappingList = new List<CommandEventMapping>()
{
new CommandEventMapping()
{
ActionType = "add",
GrowFlowCommand = new AddEmployee(),
GrowFlowEvent = "EmployeeAdded",
TraceabilityCommand = "employee_add"
}
};

cache.Set<List<CommandEventMapping>>(
"command_event_mappings", mappingList,new DistributedCacheEntryOptions()
{
AbsoluteExpiration = DateTimeOffset.Now.AddDays(1)
});

//I am able to get back the command_event_mappings here.
//Once the IDistributedCache is injected. the data is lost
var commandMapping = cache.Get<List<CommandEventMapping>>("command_event_mappings");
}

在我见过的所有示例中,通常都是这样设置的。唯一的区别是我为 Set<T> 添加了几个扩展名。和 Get<T> .我确实在没有新扩展方法的情况下进行了尝试,但结果相同。实际IDistributedCache注入(inject)的时候是可用的,但是之前缓存的数据没有了。这是我如何注入(inject)它的示例。

public LegacyCommandBus(IServiceProvider provider, IDistributedCache cache,
ITraceabilityTenantService tenantService, IHttpClientFactory httpClientFactory)
: base(provider)
{
_provider = provider;
_cache = cache;
_tenantService = tenantService;
_httpClientFactory = httpClientFactory;
//This is null
_commandEventMappings = cache.Get<List<CommandEventMapping>>("command_event_mappings");
}

最佳答案

var cache = serviceCollection.BuildServiceProvider().GetService<IDistributedCache>();

每次调用 BuildServiceProvider() 时,您都会生成一个新容器,它有自己的一组单例(不同于使用内置 DI 注入(inject)的单例)。

解决方案是在 Startup 类的 Configure 中解析 IDistributedCache 的实例。

public void Configure(IApplicationBuilder app, IDistributedCache cache) { 
//...
}

关于c# - IDistributedCache 可用但数据不再在缓存中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58081481/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com