【问题标题】:Dependency Injection problem with IMemoryCacheIMemoryCache 的依赖注入问题
【发布时间】: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,以便在创建服务时对其进行初始化。

【问题讨论】:

    标签: c# dependency-injection


    【解决方案1】:

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

    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找到更多相关信息

    【讨论】:

    • 这和我发现的很接近。我也做了这个 Services.AddSingleton(services => new ItemCache(services.GetRequiredService(), ConnectionString));它也很有效。谢谢。
    • @john 谢谢。是的,应该这样做,我仍然更喜欢在AddSingleton&lt;T&gt; 中明确声明泛型类型参数T 的类型,因为它使代码更具可读性。当您说出 AddSingleton(s =&gt; new ...) 中的 100 个时,需要一些额外的时间来了解那里实际注册的内容
    【解决方案2】:

    因此,除了 @Fabjan 的显示方式之外,您还可以简单地将 IConfiguration 注入您的 ItemCache 构造函数并在那里访问它,而不是连接字符串的字符串

    public ItemCache(IMemoryCache cache, IConfiguration config)
        {
            _cache = cache;
            connectionString = config.GetConnectionString("XXXXXX");
        }
    

    然后正常注册你的ItemCache

    services.AddSingleton<ItemCache>();
    

    【讨论】:

      猜你喜欢
      • 2015-11-21
      • 2016-05-18
      • 2014-12-27
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-02
      • 2012-06-09
      相关资源
      最近更新 更多