【发布时间】:2019-12-18 06:15:39
【问题描述】:
我正在创建一个 .net core 3.1 Worker Service 应用程序。我有一个使用 IMemoryCache 接口进行依赖注入的类。我有以下类的构造函数:
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);
});
}
现在为了注入这个,我创建了以下扩展:
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,以便在创建服务时对其进行初始化。
【问题讨论】: