0

I am new to redis. I have an instance of "Azure Cache for Redis" and try to use it in a .NET 8 client.

Here is my initialization:

// Hostname from Azure Cache for Redis
string redisHostname = "<myinstance>.redis.cache.windows.net::6380";

HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddStackExchangeRedisCache(options => {
    options.ConfigurationOptions = new ConfigurationOptions {
        EndPoints = { redisHostname }
    };

    options.ConnectionMultiplexerFactory = async () => {
        await options.ConfigurationOptions.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential()).ConfigureAwait(false);
        options.InstanceName = "MyApp";
        return await ConnectionMultiplexer.ConnectAsync(options.ConfigurationOptions).ConfigureAwait(false);
    };
});

And here is the service that uses it:

internal class TestService(IDistributedCache cache, ILogger<TestService> logger) {
    public async Task SetItem(string key, string value) {
        logger.LogInformation("Set {key}: {value}", key, value);
        await cache.SetStringAsync(key, value);
    }
    public async Task<string?> GetItem(string key) {
        var value = await cache.GetStringAsync(key);
        logger.LogInformation("Read {key}: {value}", key, value);
        return value;
    }
}

I would expect that when I use SetItem("MyKey", "MyValue") the keys stored in redis would be like "MyApp-MyKey". But that isn't the case - it's "MyKey" only.

Did I do something wrong, or does it not work in the constellation?

2 Answers 2

0

Is this just a timing problem? Try:

  builder.Services.AddStackExchangeRedisCache(options => {
+     options.InstanceName = "MyApp";
      options.ConfigurationOptions = new ConfigurationOptions {
          EndPoints = { redisHostname }
      };

      options.ConnectionMultiplexerFactory = async () => {
          await   options.ConfigurationOptions.ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential()).ConfigureAwait(false);
-         options.InstanceName = "MyApp";
          return await   ConnectionMultiplexer.ConnectAsync(options.ConfigurationOptions).ConfigureAwait(false);
      };

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

Comments

0

You have defined options.InstanceName = "MyApp" in wrong place. If you look carefully, you'd see you have placed it in ConnectionMultiplexerFactory.

So the InstanceName will not get assigned until this callback is executed, which is probably too late to make it work.

What you wanted to do is to put this line directly in callback passed to AddStackExchangeRedisCache which is executed on Redis configuration, so setting InstanceName at right time.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.