Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GeorgeTsiokos/78108f9c7d5e297084c26538bdacb312 to your computer and use it in GitHub Desktop.
Save GeorgeTsiokos/78108f9c7d5e297084c26538bdacb312 to your computer and use it in GitHub Desktop.
Use same same Redis connection for IDistributedCache and DataProtection
public static class DataProtectionBuilderExtensions
{
public static IDataProtectionBuilder PersistKeysToStackExchangeRedisCache(this IDataProtectionBuilder builder, RedisKey key)
{
builder.Services.AddOptions<KeyManagementOptions>()
.Configure<IDistributedCache>((options, distributedCache) => options.XmlRepository = new RedisXmlRepository(() => GetDatabase(distributedCache), key));
return builder;
}
private static IDatabase GetDatabase(IDistributedCache store)
{
const BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
var redisCache = (RedisCache)store;
var redisCacheType = typeof(RedisCache);
var connectMethod = redisCacheType.GetMethod("Connect", bindingFlags);
var cacheField = redisCacheType.GetField("_cache", bindingFlags);
connectMethod.Invoke(redisCache, null);
return (IDatabase)cacheField.GetValue(redisCache);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment