Is this Lazy <T> considered single?
I need to be able to call this method
IDatabase cache = CacheConnectionHelper.Connection.GetDatabase();
From anywhere in my application I got this connection helper class from one 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 arises:
- Is the above singleton and if not then how do I change it so that every time I try to get a connection it only uses one instance and doesn't try to open more than one connection.
source to share
Yes, that's a singleton, because it Lazy<T>
makes sure your factory delegate
return ConnectionMultiplexer.Connect(SettingsHelper.AzureRedisCache);
... is called only once. It will be called on the first reading lazyConnection.Value
. The remaining calls will return the same value / instance that was returned from the first call (it is cached).
For clarity, I would do 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.
source to share
That's right, it's a singleton.
If you are using .NET 4 (or higher) you can use System.Lazy to make lazy really easy. All you have to do is pass a delegate to the constructor, which calls the Singleton constructor - which is most easily accomplished 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()
{
}
}
It also allows you to check if the instance has already been created with the IsValueCreated property , if you need to.
source to share