Skip to content

Instantly share code, notes, and snippets.

Created October 26, 2017 06:08
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 anonymous/c7c741b8a97e2c77e4bc3eeb9d4781ec to your computer and use it in GitHub Desktop.
Save anonymous/c7c741b8a97e2c77e4bc3eeb9d4781ec to your computer and use it in GitHub Desktop.
This is a Singleton Redis Helpr I am using that creates a bunch of Connection issues. Is there a better way?
public sealed class RedisHelper
{
private static RedisHelper _instance;
private static readonly Lazy<RedisHelper> Lazy = new Lazy<RedisHelper>(() => new RedisHelper());
private static readonly object SyncRoot = new object();
private static string RedisSource = string.Empty;
public static ConnectionMultiplexer RedisConnection;
public IDatabase RedisDb;
private RedisHelper()
{
var connStr = ConfigurationManager.AppSettings[TsConstants.AppSettingKeyNames.RedisCacheConnection];
if (connStr == null) throw new ArgumentException("Redis Connection not setup.");
//creating this RedisSource to track a connection in logs to see if multiple connections are being created or not
RedisSource = ConfigurationManager.AppSettings[TsConstants.AppSettingKeyNames.RedisSource];
RedisSource = $"{RedisSource}-{new Random().Next(int.MaxValue)}";
if (RedisConnection == null || !RedisConnection.IsConnected)
{
RedisConnection = ConnectionMultiplexer.Connect(configOptions);
Log.Logger.Information($"Source: {RedisSource} - Built a new Redis Connection");
}
RedisConnection.PreserveAsyncOrder = true;
RedisDb = RedisConnection.GetDatabase();
}
public static RedisHelper Instance
{
get
{
if (_instance == null)
lock (SyncRoot)
{
return Lazy.Value;
}
return _instance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment