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

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注入时可用,但先前缓存的数据已消失。
这是我如何注射的一个例子。

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注入的单例不同)。

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

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

07-24 18:41