ASP.NET Core—access Configuration from static class

后端 未结 13 2006
我在风中等你
我在风中等你 2021-02-01 00:27

I want a simple static class that accesses the Configuration object. All the config info is already read in from the appsettings.json file in the Startup class. I just need an e

13条回答
  •  有刺的猬
    2021-02-01 00:52

    Try avoid using a static class and use DI

    namespace MyNamespace {
    
      public interface IConfig {
        string Username { get; }
        string Password { get; }
      }
    
    
      public class Config : IConfig {
        public Config(IConfiguration configuration) {
          _configuration = configuration;
        }
        readonly IConfiguration _configuration;
        public string Username => _configuration["Username"];
        public string Password => _configuration["Password"];
      }
    
    
    }
    

    The setup DI in StartUp class

    public class Startup {
      public void ConfigureServices(IServiceCollection services) {
        //...
        services.AddTransient(); 
        ...
      }
    }
    

    And use it like so

      public class TestUsage {
        public TestUsage(IConfig config) {
          _config = config;
        }
        readonly IConfig _config;
        public string Username => _config.Username;
        public string Password => _config.Password;
      }
    

提交回复
热议问题