Access to configuration without dependency injection

后端 未结 3 1235
予麋鹿
予麋鹿 2020-12-29 01:51

I was wondering if there was a way to access Configuration (Microsoft.Extensions.Configuration) without the use of dependency injection. Only examples I see are through con

3条回答
  •  长情又很酷
    2020-12-29 02:34

    I am totally agree with solution suggested by @Hoot but i have modified class little. i have modified class because i need to pass dynamic Key to fetch value for same..

    Configuration Class :

    public class ConfigHelper
        {
    
            private static ConfigHelper _appSettings;
    
            public string appSettingValue { get; set; }
    
            public static string AppSetting(string Key)
            {
              _appSettings = GetCurrentSettings(Key);
              return _appSettings.appSettingValue;
            }
    
            public ConfigHelper(IConfiguration config, string Key)
            {
                this.appSettingValue = config.GetValue(Key);
            }
    
            public static ConfigHelper GetCurrentSettings(string Key)
            {
                var builder = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                .AddEnvironmentVariables();
    
                IConfigurationRoot configuration = builder.Build();
    
                var settings = new ConfigHelper(configuration.GetSection("AppSettings"), Key);
    
                return settings;
            }
        }
    

    Appsettings.Json Configuration:

     "AppSettings": {
        "WebApplicationUrl": "http://localhost:0000/",
        "ServiceUrl": "http://localhost:0000/",
        "CommonServiceUrl": "http://localhost:0000/"
      }
    

    Calling Example:

    string ServiceUrl = ConfigHelper.AppSetting("ServiceUrl");
    

    So from now we are able to pass dynamic key.

提交回复
热议问题