c# - Is this Lazy<T> considered a singleton? -


i need able call method

idatabase cache = cacheconnectionhelper.connection.getdatabase(); 

from anywhere on application, got connection helper class azure page

public class cacheconnectionhelper     {         private static lazy<connectionmultiplexer> lazyconnection = new lazy<connectionmultiplexer>(() =>         {             return connectionmultiplexer.connect(settingshelper.azurerediscache);         });          public static connectionmultiplexer connection         {                         {                 return lazyconnection.value;             }         }     } 

the question is:

  1. is above singleton , if not how should change it, each time try connection, using 1 instance , doesnt try open more 1 connection

yes, that's singleton because lazy<t> makes sure factory delegate

return connectionmultiplexer.connect(settingshelper.azurerediscache); 

...is invoked once. invoked first time lazyconnection.value read. remaining invocations return same value/instance returned first invocation (it cached).

for clarity, make cacheconnectionhelper static:

public static class cacheconnectionhelper 

by way, looks code copied this msdn article.

this provides thread-safe way initialize single connected connectionmultiplexer instance.


Comments