title: What is the Best Practice to configure StackExchange.Redis with Autofac?
body: <p>In the <a href="https://github.com/StackExchange/StackExchange.Redis/blob/master/Docs/Basics.md" rel="noreferrer">StackExchange.Redis docs</a> it is recommended to only create one and reuse the connection to Redis.</p>
  
  <p><a href="http://azure.microsoft.com/blog/2015/02/10/investigating-timeout-exceptions-in-stackexchange-redis-for-azure-redis-cache/" rel="noreferrer">Azure Redis best practices</a> recommends using the following pattern:</p>
  
  <pre><code>private static Lazy&lt;ConnectionMultiplexer&gt; lazyConnection = new Lazy&lt;ConnectionMultiplexer&gt;(() =&gt;
  {
      return ConnectionMultiplexer.Connect("cachename.redis.cache.windows.net,ssl=true,abortConnect=false,password=password");
  });
  
  public static ConnectionMultiplexer Connection
  {
      get
      {
          return lazyConnection.Value;
      }
  }
  </code></pre>
  
  <p>but how should I get this working with Autofac where I want the configuration to be set in the web/app config files?</p>
  
  <p>I currently have a RedisCacheProvider:</p>
  
  <pre><code>private readonly ConnectionMultiplexer _connection;
  
  public RedisCacheProvider(string config)
  {
      _connection = ConnectionMultiplexer.Connect(config);
  }
  </code></pre>
  
  <p>and in my Autofac config:</p>
  
  <pre><code>builder.RegisterType&lt;RedisCacheProvider&gt;().As&lt;ICacheProvider&gt;().WithParameter("config", "localhost");
  </code></pre>
  
  <p>My thinking is, I should change my RedisCacheProvider to take in a ConnectionMultiplexer which is passed in via the static variable?</p>
  
  <p><strong>Update: My Solution so far:</strong></p>
  
  <p>My RedisCacheProvider (injecting an interface here allows me to mock the connection in unit tests):</p>
  
  <pre><code>private readonly IConnectionMultiplexer _connection;
  
  public RedisCacheProvider(IConnectionMultiplexer connection)
  {
     _connection = connection;
  }
  </code></pre>
  
  <p>RedisConnection class to hold the static property and read config from config file:</p>
  
  <pre><code>public class RedisConnection
  {
      private static readonly Lazy&lt;ConnectionMultiplexer&gt; LazyConnection = 
          new Lazy&lt;ConnectionMultiplexer&gt;(
              () =&gt; ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisCache"]));
  
      public static ConnectionMultiplexer Connection
      {
          get
          {
              return LazyConnection.Value;
          }
      }
  }
  </code></pre>
  
  <p>Registration in an Autofac Module:</p>
  
  <pre><code>builder.RegisterType&lt;RedisCacheProvider&gt;().As&lt;ICacheProvider&gt;()
                      .WithParameter(new TypedParameter(
                                         typeof(IConnectionMultiplexer), 
                                         RedisConnection.Connection));
  </code></pre>