How can one implement a Singleton that populates its values ​​from db in C #?

I am trying to implement a Jon Skeet example

public sealed class Singleton
{
    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return Nested.instance;
        }
    }

    class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}
+3
source share
2 answers

Perform all database operations in the constructor for Singleton.

Not knowing what these operations are, we cannot provide you with more additional assistance, but you must place them. Obviously, this does not mean creating a massive constructor - you can still break the code into regular methods, but you need to call them from the constructor.

+4
source

Almost direct copy using BlogEngine ...

    System.Collections.Specialized.ListDictionary lstSettings;
    string msg; 

    MyApp.Bo.AppUser objAppUser = new AppUser();
    MyApp.Db.SqlServer2008Provider p = new MyApp.Db.SqlServer2008Provider(objAppUser);



    p.LoadSettings(out msg, out lstSettings); 

    foreach (string key in lstSettings.Keys)
    {

        string name = key;
        string value = (string)lstSettings[key];

        #region CycleTroughobjAppSettingProperties
        Type objAppSettingsType = typeof(MyApp.Bo.AppSettings);
        foreach (PropertyInfo propInfo in objAppSettingsType.GetProperties())
        {
            if (propInfo.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
            {

                try
                {
                    propInfo.SetValue(this, Convert.ChangeType(value, propInfo.PropertyType, CultureInfo.CurrentCulture), null);
                }
                catch
                {
                    logger.Fatal("Failed setting the Application settings ");
                }
                break;
            }
        }
        #endregion CycleTroughobjAppSettingProperties
    }
0
source

Source: https://habr.com/ru/post/1709774/


All Articles