Azure Redis StackExchange.Redis ConnectionMultiplexer in ASP.net MVC

I read that to connect to the Azure Redis cache it is best to follow this practice:

private static ConnectionMultiplexer Connection { get { return LazyConnection.Value; } } private static readonly Lazy<ConnectionMultiplexer> LazyConnection = new Lazy<ConnectionMultiplexer>( () => { return ConnectionMultiplexer.Connect(connStinrg); }); 

And according to Azure Redis docs:

The connection to the Azure Redis cache is controlled by the ConnectionMultiplexer class. This class is intended to be shared and reused in your client application, and it does not need to be created based on each operation.

So what is the best way to use ConnectionMultiplexer in my ASP.net MVC application? Should it be called in Global.asax, or should I initialize it once to the controller or smth. else?

I also have a service that is instructed to communicate with the application, so if I want to communicate with Redis inside the Service, should I send an instance of ConnectionMultiplexer for service from the controllers or initialize it in all my services or?

As you can see, I got a little lost here, so please help!

+7
c # asp.net-mvc redis stackexchange.redis azure-redis-cache
source share
2 answers

The docs are correct in that you should only have one instance of ConnectionMultiplexer and reuse it. Do not create more than one; it is recommended that it be transferred and reused .

Now for the creation part, it does not have to be in the Controller or in Global.asax. Usually you should have your own RedisCacheClient class (possibly implementing some ICache interface) that uses a private static instance of ConnectionMultiplexer inside and where your creation code should be - exactly as you wrote it in your question. The Lazy component will delay the creation of ConnectionMultiplexer until first use.

+6
source share

Dears

You can reuse StackExchange.Redis ConnectionMultiplexer using the following code. It can be used at any level of your code.

 public class RedisSharedConnection { private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() => { ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(ConfigurationManager.ConnectionStrings["RedisConnectionString"].ConnectionString); connectionMultiplexer.PreserveAsyncOrder = false; return connectionMultiplexer; }); public static ConnectionMultiplexer Connection { get { return lazyConnection.Value; } } } 
0
source share

All Articles