Add support for keyed IDistributedCache in AddStackExchangeRedisCache
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 6h
- Merged PRs (30d)
- 290
Description
## Background and Motivation
We have been finding scenarios where developers need multiple IDistributedCache instances in a single application. For example:
* https://github.com/dotnet/aspire/issues/8528
* https://github.com/dotnet/runtime/issues/117976
One concrete example is to have 2 IDistributedCache instances, one pointing to Redis and one pointing to a SqlServer. Another example is 2 caches talking to different instances of Redis.
## Proposed API
```diff
namespace Microsoft.Extensions.DependencyInjection;
public static class StackExchangeRedisCacheServiceCollectionExtensions
{
public static IServiceCollection AddStackExchangeRedisCache(this IServiceCollection services, Action setupAction);
+ public static IServiceCollection AddKeyedStackExchangeRedisCache(this IServiceCollection services, object? key, Action setupAction);
+ public static IServiceCollection AddKeyedStackExchangeRedisCache(this IServiceCollection services, object? serviceKey, string optionsName, Action setupAction);
}
```
This follows the same API approach (the optional `optionsName`) as proposed in https://github.com/dotnet/runtime/issues/117976
## Usage Examples
```csharp
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddKeyedStackExchangeRedisCache("cache1", options =>
{
options.Configuration = "redis1:6379";
options.InstanceName = "SampleInstance1";
});
builder.Services.AddKeyedStackExchangeRedisCache(typeof(MyCache), "myCacheOptionsName", options =>
{
options.Configuration = "redis2:6379";
options.InstanceName = "SampleInstance2";
});
var app = builder.Build();
var cache1 = app.Services.GetRequiredKeyedService("cache1");
var cache2 = app.Services.GetRequiredKeyedService(typeof(MyCache));
```
## Alternative Designs
## Risks
The current approach being employed is to create a new `RedisCache` instance (since the ctor is public). However, the when using `AddStackExchangeRedisCache` today it uses an internal derived type: `RedisCacheImpl`.
As of .NET 10, the drawback to this approach is that it doesn't use the internal RedisCacheImpl class. Which means:
- The RedisCache won't log appropriately (but it only logs in one place - where it is unable to add library name suffix).
- If HybridCache is being used, it won't add the 'HC' library name suffix to the connection. Since the check only happens in RedisCacheImpl.
FYI @mgravell @jeffhandley @captainsafia
Contributor guide
Assessment
This issue has not been assessed yet.