Use ConfigDescriptor to read config

Scenario:

Use ConfigDescriptor to read config

Solution:

  • Read the config
    1.  1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      namespace 
      {
          [Serializable]
          public class UserConfigs
          {
             public class UserConfig
              {
                  public UserConfig(string role, bool isActive)
                  {
                      Role = role;
                      IsActive = isActive;
                  }
      
                  public string Role { get; }
      
                  public bool IsActive { get; }
              }
      
              private Dictionary<string, UserConfig> _userConfigs;
      
              public void Load(string config)
              {
                  //Deserialize config section
      
                  _userConfigs = configs.Users
                      .Cast<User>()
                      .ToDictionary(u => u.Name,
                          u => new UserConfig(u.Role, u.IsActive),
                          StringComparer.InvariantCultureIgnoreCase);
              }
      
              public bool TryGetUserConfig(string name, out UserConfig userConfig)
              {
                  try
                  {
                      return _userConfigs.TryGetValue(name, out userConfig);
                  }
                  catch
                  {
                      userConfig = default(UserConfig);
                      return false;
                  }
              }
          }
      }
  • Call the config
    1. 1
      2
      3
      4
      5
      6
      7
      private static UserConfig GetConfig(string name)
      {
           if (!config.TryGetUserConfig(name, out var userConfig))
          {
          }
          return userConfig;
      }
  • Use the config
    1
    2
    3
    4
    5
    public Process ()
    {
        var config = GetConfig("users");
        var role = config.Role;
    }

No comments:

Post a Comment

Move Github Sub Repository back to main repo

 -- delete .gitmodules git rm --cached MyProject/Core git commit -m 'Remove myproject_core submodule' rm -rf MyProject/Core git remo...