gpt4 book ai didi

c# - IMemoryCache 的依赖注入(inject)问题

转载 作者:行者123 更新时间:2023-12-04 13:17:03 25 4
gpt4 key购买 nike

我正在创建一个 .net core 3.1 Worker Service 应用程序。我有一个使用 IMemoryCache 接口(interface)进行依赖注入(inject)的类。我有以下类的构造函数:

 public ItemCache(IMemoryCache cache, string ConnectionString)
{
_cache = cache;
connectionString = ConnectionString;
}

我的代码使用 GetOrCreateAsync 方法为缓存创建条目:

 public async Task<OrderItem> GetItem(string itemId, string clientName)
{
//check for item in cache, if not there grab it from the database add it and return
return await _cache.GetOrCreateAsync(itemId, async entry =>
{
entry.SetSlidingExpiration(TimeSpan.FromHours(8));
return await GetItemFromDB(itemId, clientName);
});
}

现在为了注入(inject)这个,我创建了以下扩展:

public static class ItemCacheExtensions
{
public static void AddItemCache(this IServiceCollection Services, string ConnectionString, IMemoryCache cache)
{
Services.AddSingleton(services => new ItemCache(cache, ConnectionString));
}
}

我遇到的问题是在 Program.cs 文件中,在 CreateHostBuilder 方法中添加服务:

services.AddItemCache(hostContext.Configuration.GetConnectionString("XXXXXX"));

我正在努力寻找如何在调用中传递 IMemoryCache,以便在创建服务时对其进行初始化。

最佳答案

您应该能够使用接受 IServiceProvider 作为参数的方法 AddSingleton 的另一个重载来获取它:

serivces.AddSingleton<IMemoryCache, MemoryCache>();

public static class ItemCacheExtensions
{
public static void AddItemCache(this IServiceCollection Services, string ConnectionString, IMemoryCache cache)
{
Services.AddSingleton<ItemCache>(serviceProvider => {
var cache = serviceProvider.GetService(typeof(IMemoryCache));
return new ItemCache(cache, ConnectionString);
});
}
}

您可以在 official documentation 中找到更多相关信息

关于c# - IMemoryCache 的依赖注入(inject)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59382511/

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