Ensure Singleton call db query only once

c#, singleton

Solution

1) Is this thread safe?

Yes.

Are there any chances DB will be query multiple times?

No.

2) Should I use await and async?

That will depend on whether you need asynchronous access to your database. If you need that you could use the async ADO.NET API.

Problem

I'm trying to create one object that will be responsible for reading all users access settings. I've created class as so: ``` public class SettingsManager { private static string _connString = @"Data Source=MyDB;Initial Catalog=IT;Integrated Security=True;Asynchronous Processing=true;"; private const string _spName = "SettingTest"; private IEnumerable<string> _mySettings; private static readonly Lazy<SettingsManager> _instance = new Lazy<SettingsManager>(() => new SettingsManager()); private SettingsManager() { //Console.WriteLine("Hello from constructor"); if (_mySettings == null) _mySettings = ReadSettings(); } public static SettingsManager Instance { get { return _instance.Value; } } public bool CanDo(string setting) { return _mySettings.Contains(setting); } private IEnumerable<string> ReadSettings() { try { using (var conn = new SqlConnection(_connString)) { using (var cmd = new SqlCommand()) { cmd.Connection = conn; cmd.CommandText = _spName; cmd.CommandType = CommandType.StoredProcedure; conn.Open(); using (var reader = cmd.ExecuteReader()) { return reader.Select(SettingParser).ToList(); } } } } catch { } return null; } private string SettingParser(SqlDataReader r) { try { return r[0] is DBNull ? null : r[0].ToString(); } catch { } return null; } } ``` And SqlDataReader Extension ``` public static class DBExtensions { public static IEnumerable<T> Select<T>( this SqlDataReader reader, Func<SqlDataReader, T> projection) { while (reader.Read()) { yield return projection(reader); } } } ``` Then inside my application I'm able to call it as so: ``` SettingsManager.Instance.CanDo("canWrite") ``` this returns true/false value depends on user access level. My questions are: Is this thread safe? Are there any chances DB will be query multiple times? How to prevent this? Should I use await and async? I query db just once. How can I improve this? (await and async are really new to me because I just moved from .NET3.5 to 4.5)

Original source