【问题标题】:Dependency injection in DbCommandInterceptorDbCommandInterceptor 中的依赖注入
【发布时间】:2020-09-04 16:14:47
【问题描述】:

我正在尝试将 Azure Redis 缓存添加到我的应用程序。我试图用拦截器来做,所以当查询完成时,如果结果存在于缓存中,我会替换结果并少做一次查询,否则我会得到查询结果并将其存储在缓存中. 当然,我只在涉及某些表时才这样做。 我已将 Redis 缓存添加到我的启动中:

services.AddDistributedRedisCache(config =>
        {
            config.Configuration = GetAppSettingsValue("RedisConnectionString", Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"));
        });

现在我需要在我的拦截器中使用它:

public class RedisCacheInterceptor : DbCommandInterceptor
{
    private readonly IDistributedCache _distributedCache;

    public RedisCacheInterceptor(IDistributedCache distributedCache)
    {
        _distributedCache = distributedCache;
    }
}

此时,当我尝试将拦截器添加到数据库连接时,我不知道如何使用依赖注入来实例化拦截器。

我应该如何解决这个问题? 我是否以错误的方式使用拦截器?

【问题讨论】:

    标签: .net-core dependency-injection interceptor ef-core-3.1 ef-core-3.0


    【解决方案1】:

    这并不能回答您使用拦截器的问题,但也许这种模式可能会有所帮助。查看此代码:

    private async Task<T> GetFromCacheOrDownloadAsync<T>(string cacheKey, Func<Task<T>> initializeFunction)
    {
        bool cacheAvailable;
        try
        {
            await Connect();
            var value = await _database.StringGetAsync(cacheKey);
            if (!string.IsNullOrEmpty(value))
            {
                return JsonSerializer.Deserialize<T>(value);
            }
    
            cacheAvailable = true;
        }
        catch (Exception)
        {
            _logger.LogWarning("Oops, apparently your cache is down...");
            cacheAvailable = false;
        }
    
        var downloadedObject = await initializeFunction();
        var jsonValue = JsonSerializer.Serialize(downloadedObject);
    
        if (cacheAvailable)
        {
            await _database.StringSetAsync(cacheKey, jsonValue);
        }
    
        return downloadedObject;
    }
    

    我调用它来从 Redis 缓存中获取“某些东西”。当数据不存在时,我还传递了一个初始化函数来调用。所以基本上:

    • 从缓存中获取数据
    • 如果数据不存在,请使用其他函数获取数据
    • 添加到缓存

    查看这个包含这个例子的演示 repo:

    https://github.com/4DotNet/WebCasts-Caching

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-08
      • 2014-06-12
      • 2013-04-10
      • 2010-11-27
      相关资源
      最近更新 更多