这个 Lazy<T> 算单例吗?

Is this Lazy<T> considered a singleton?

我需要能够调用这个方法

IDatabase cache = CacheConnectionHelper.Connection.GetDatabase();

在我的应用程序的任何地方,我从某个 azure 页面

得到了这个连接助手 class
public class CacheConnectionHelper
    {
        private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            return ConnectionMultiplexer.Connect(SettingsHelper.AzureRedisCache);
        });

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

问题是:

  1. 是上面的单例吗?如果不是,我应该如何改变它,这样每次我尝试获取一个连接时,它只使用一个实例并且不会尝试打开多个连接

正确,是单例

参考:using .NET 4's Lazy type

If you're using .NET 4 (or higher), you can use the System.Lazy type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor - which is done most easily with a lambda expression.

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

如果需要,它还允许您使用 IsValueCreated property 检查实例是否已创建。

是的,那是一个单例,因为 Lazy<T> 确保你的工厂代表

return ConnectionMultiplexer.Connect(SettingsHelper.AzureRedisCache);

...只调用一次。它将在第一次读取 lazyConnection.Value 时被调用。其余调用将 return 与第一次调用 return 相同的 value/instance(已缓存)。

为清楚起见,我将 CacheConnectionHelper 设为静态:

public static class CacheConnectionHelper

顺便说一下,您的代码似乎是从 this MSDN article 复制而来的。

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