簡體   English   中英

ASP.NET Core 2 - 多個Azure Redis緩存服務DI

[英]ASP.NET Core 2 - Multiple Azure Redis Cache services DI

在ASP.NET Core 2中,我們可以像這樣添加Azure Redis緩存:

 services.AddDistributedRedisCache(config =>
 {
    config.Configuration = Configuration.GetConnectionString("RedisCacheConnection");
    config.InstanceName = "MYINSTANCE";
 });

那么用法將是這樣的:

private readonly IDistributedCache _cache;

public MyController(IDistributedCache cache)
{
   _cache = cache;
}

我該怎么辦才能擁有:

private readonly IDistributedCache _cache1;
private readonly IDistributedCache _cache2;

public MyController(IDistributedCache cache1, IDistributedCache cache2)
{
   _cache1 = cache1;
   _cache2 = cache2;
}

我的問題如何添加另一個指向不同的Azure Redis緩存連接和實例的服務,並在我想使用它們時將它們分開?

在場景后面, AddDistributedRedisCache()擴展方法執行以下操作( github上的代碼 ):

  1. 注冊配置RedisCacheOptions 您傳遞給AddDistributedRedisCache() Lambda負責。 RedisCacheOptions實例傳遞給包裝在IOptions<T>RedisCache構造函數。
  2. 寄存器Singletone實施RedisCacheIDistributedCache接口。

不幸的是,這兩種行為都不適合你的要求。 只能注冊一個操作來配置特定類型的選項。 .net核心依賴注入的本機實現不支持注冊覆蓋。

仍然有一個解決方案可以做你想要的。 然而這個解決方案有點讓我傷心

訣竅是您從RedisCacheOptions繼承自定義RedisCacheOptions1,RedisCacheOptions2並為它們注冊不同的配置。

然后定義從IDistributedCache繼承的自定義IDistributedCache1和IDistributedCache2接口。

最后,您定義了類RedisCache1(它繼承了RedisCache的實現,並實現了IDistributedCache1)和RedisCache2(相同)。

像這樣的東西:

public interface IDistributedCache1 : IDistributedCache
{
}

public interface IDistributedCache2 : IDistributedCache
{
}

public class RedisCacheOptions1 : RedisCacheOptions
{
}

public class RedisCacheOptions2 : RedisCacheOptions
{
}

public class RedisCache1 : RedisCache, IDistributedCache1
{
    public RedisCache1(IOptions<RedisCacheOptions1> optionsAccessor) : base(optionsAccessor)
    {
    }
}

public class RedisCache2 : RedisCache, IDistributedCache2
{
    public RedisCache2(IOptions<RedisCacheOptions2> optionsAccessor) : base(optionsAccessor)
    {
    }
}

public class MyController : Controller
{
    private readonly IDistributedCache _cache1;
    private readonly IDistributedCache _cache2;

    public MyController(IDistributedCache1 cache1, IDistributedCache2 cache2)
    {
        _cache1 = cache1;
        _cache2 = cache2;
    }
}

//  Bootstrapping

services.AddOptions();

services.Configure<RedisCacheOptions1>(config =>
{
    config.Configuration = Configuration.GetConnectionString("RedisCacheConnection1");
    config.InstanceName = "MYINSTANCE1";
});
services.Configure<RedisCacheOptions2>(config =>
{
    config.Configuration = Configuration.GetConnectionString("RedisCacheConnection2");
    config.InstanceName = "MYINSTANCE2";
});

services.Add(ServiceDescriptor.Singleton<IDistributedCache1, RedisCache1>());
services.Add(ServiceDescriptor.Singleton<IDistributedCache2, RedisCache2>());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM