Search code examples
c#azuresingletonstackexchange.redisazure-redis-cache

Is this Lazy<T> considered a singleton?


I need to be able to call this method

IDatabase cache = CacheConnectionHelper.Connection.GetDatabase();

From anywhere on my application, I got this connection helper class from some azure page

public class CacheConnectionHelper
    {
        private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            return ConnectionMultiplexer.Connect(SettingsHelper.AzureRedisCache);
        });

        public static ConnectionMultiplexer Connection
        {
            get
            {
                return lazyConnection.Value;
            }
        }
    }

The question is:

  1. Is the above singleton and if not how should I change it, so that each time that I try get a Connection, its only using one instance and doesnt try to open more than one connection

Solution

  • Yes, that's a singleton because Lazy<T> makes sure that your factory delegate

    return ConnectionMultiplexer.Connect(SettingsHelper.AzureRedisCache);
    

    ...is only invoked once. It will be invoked the first time lazyConnection.Value is read. Remaining invocations will return the same value/instance that was returned from the first invocation (it is cached).

    For clarity, I would make CacheConnectionHelper static:

    public static class CacheConnectionHelper
    

    By the way, it looks like your code is copied from this MSDN article.

    This provides a thread-safe way to initialize only a single connected ConnectionMultiplexer instance.