C# – The correct way of using StackExchange.Redis


The idea is to use less connection and better performance.
Does the connection expire at any time?

And for another question, does _redis.GetDatabase() open new connection?

private static ConnectionMultiplexer _redis;
private static IDatabase _db;

public RedisCacheProvider(string configuration)
    if (_redis == null)
        lock (myLock)
            if (_redis == null)
                _redis = ConnectionMultiplexer.Connect(configuration);
                _db = _redis.GetDatabase();

public async Task<string> GetString(string key)
    string result = null;

    RedisValue val = await _db.StringGetAsync(key);

    if (val.HasValue)
        result = val;

    return result;

Best Solution

No, a multiplexer doesn't expire. No GetDatabase doesn't open a new connection. This is all covered in basics.md - in particular:

The object returned from GetDatabase is a cheap pass-thru object, and does not need to be stored.