Created
April 8, 2019 15:21
-
-
Save GeorgeTsiokos/78108f9c7d5e297084c26538bdacb312 to your computer and use it in GitHub Desktop.
Use same same Redis connection for IDistributedCache and DataProtection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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