1

I have a Redis instance and I want StackExchange.Redis to connect to that specific instance, but I am unable to find any configuration to set the InstanceName!

1 Answer 1

2

You can have an extension method like this:

public static IServiceCollection AddRedisQueue(this IServiceCollection services, IConfiguration configuration)
    {
        var options = configuration.GetOptions<RedisOptions>(SectionName);
        var multiplexer = ConnectionMultiplexer.Connect(options.ConnectionString);
        services.AddSingleton<IConnectionMultiplexer>(multiplexer);

        return services;
    }

Where RedisOptions is a class like this and section name is redis config name in your settings file:

public class RedisOptions
{
    public string ConnectionString { get; set; }
    public string Instance { get; set; }
}

Then you can inject it in Startup.cs ConfigureServices method like this:

services.AddRedisQueue(Configuration);

Later in code you just inject IConnectionMultiplexer from the constructor of the class where you would like to use redis, and get database by calling IConnectionMultiplexer's GetDatabase() method. About Instance property of redis options, you use it when providing a key:

var key = $"{redisOptions.Value.Instance}some_key";

Then use this key when dealing with IDatabase instance of stack exchange.

Sign up to request clarification or add additional context in comments.

3 Comments

Would you please elaborate on where should I use the property "Instance" of RedisOptions? This property is not used in AddRedisQueue in the code you have kindly provided. @Aspram
I see, many thanks. Is there any configuration that I can set so that I will not have to add the "Instance name" manually every time? @Aspram
As long as I know you can have that only when using IDistributedCache.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.